typescript - 打字稿通用转换函数
问题描述
我在 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'.
解决方案
这个函数签名:
foo<T>(arg: T): T
返回与其参数相同的类型。这意味着如果您传入 string "Sebastian"
,您希望"Sebastian"
返回,而不仅仅是任何字符串。但是按照您编写此函数的方式,它会返回"hello"
,它具有不同的字符串文字类型。
为了支持这个逻辑,我认为函数重载是你想要的。您将为返回字符串的字符串创建一个特殊的调用签名,然后为处理所有其他参数类型的通用调用签名。
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 }
推荐阅读
- android - 了解允许/拒绝的权限
- xml - 将标签添加到 xml 而不更改其他标签 javax.xml
- c++ - 函数模板参数是带默认参数的类模板时,模板参数推导如何执行
- c# - 将几何转换为地理的实体框架
- api - www.crypto.com 身份验证,python HMAC-SHA256
- excel - 根据 B 列中的字符串条件对 A 列的值求和
- java - 无法获取上传图像到 Firebase android 的下载 URL
- sql - 如何在 SQL 中遍历表的子集
- python - 如何在 DAG (pandas\networkx) 上获取所有连接边的链
- eclipse - Windows 上的 OMNeT++ 5.5.1 和 SimuLTE - 调试错误