假设我像这样定义类型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>() => {
上,我从编译器收到一个错误,告诉我
'字符串'已声明,但其值从未读过。ts(6133)参数输入'()=> {message:string;结果:字符串; }' 不是可分配给“ CoolFunction”类型的参数。通话签名返回类型'{message:string;结果:字符串; }”和“ CoolType”不兼容。“结果”的类型在这些类型之间是不兼容的。类型“字符串”不可分配给类型“ T”。'string'可以分配给'T'类型的约束,但是'T'可以用不同的约束子类型实例化'{}'。ts(2345)
知道我在做什么错吗?这是一个重现该错误的stackblitz。
您似乎在错误的位置使用了仿制药。我认为您想要的是:
type CoolFunction<T> = () => CoolType<T>;
即CoolFunction
也采用通用类型。然后,您的高阶函数可以传播泛型:
function superCoolFunction<T>(coolFunction: CoolFunction<T>): CoolType<T> {
return coolFunction();
}
现在特定类型可以由编译器推断:
superCoolFunction(() => ({ message: 'foo', result: 123 }));
// function superCoolFunction<number>(coolFunction: CoolFunction<number>): CoolType<number>
或明确提供:
superCoolFunction<string>(() => ({ message: 'foo', result: 'bar' }));