如何解决Typescript通用转换函数
我正在打字稿v4.0.2中使用泛型,并且遇到了这种奇怪的情况。当我缩小T
的范围后,为什么编译器会抱怨string
不是function foo<T>(arg: T): T {
if (typeof arg === "string") {
return "hello"
}
return arg
}
?
Type 'string' is not assignable to type 'T'.
'T' could be instantiated with an arbitrary type which could be unrelated to 'string'.
错误是:
<div class="list">
<div class="card"><h5>First Task</h5></div>
<div class="card"><h5>Second Task</h5></div>
<div class="card"><h5>Third Task</h5></div>
<div class="card"><h5>Fourth Task</h5></div>
</div>
.list {
width: 600px;
height: 400px;
background-color: yellow;
display: flex;
flex-wrap: wrap;
}
.card {
background-color: blue;
border: solid black 2px;
flex: 0 0 185px;
height: 69px;
}
解决方法
此功能签名:
foo<T>(arg: T): T
返回与其参数相同的类型。这意味着,如果您传递字符串"Sebastian"
,则不仅会返回任何字符串,而且还会返回"Sebastian"
。但是,按照您编写此函数的方式,它将返回"hello"
,它具有不同的字符串文字类型。
为支持此逻辑,我认为function overloads是您想要的。您将只为返回字符串的字符串创建一个特殊的调用签名,然后再处理所有其他参数类型的通用调用签名。
function foo(arg: string): "hello"
function foo<T>(arg: T): T
function foo<T>(arg: T): T | "hello" {
if (typeof arg === "string") {
return "hello"
}
return arg
}
const a = foo('testing') // type: "hello"
const b = foo(123) // type: 123
const c = foo(123 as number) // type: number
const d = foo({ abc: 123 }) // type: { abc: 123 }
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。