【发布时间】:2020-06-12 21:03:47
【问题描述】:
假设我这样定义一个类型CoolType:
type CoolType<T> = {message: string, result: T}
然后我定义一个CoolFunction类型来描述一个返回CoolType的函数:
type CoolFunction = <T>() => CoolType<T>
CoolFunction 是第二个函数期望的参数类型:
function superCoolFunction(coolFunction: CoolFunction) {
return coolFunction()
}
最终,在所有这些定义之后,我尝试运行一些这样的代码:
const res = superCoolFunction(<string>() => {
return {message: 'I am the message', result: 'I am the result'}
})
但是,在上述代码的<string>() => { 上,我从编译器那里得到一个错误,告诉我
'string' 已声明,但它的值永远不会被读取。ts(6133) 的参数 类型 '() => { 消息:字符串;结果:字符串; }' 不是 可分配给“CoolFunction”类型的参数。来电签名 返回类型'{消息:字符串;结果:字符串; }' 和 'CoolType' 不兼容。 这些类型之间的“结果”类型不兼容。 类型“字符串”不可分配给类型“T”。 “字符串”可分配给“T”类型的约束,但“T”可以用不同的约束子类型实例化 '{}'.ts(2345)
知道我做错了什么吗?这是重现错误的stackblitz。
【问题讨论】:
标签: typescript typescript-typings typescript-generics