我有map
功能:
const map = <T, U>(f: (x: T) => U, arr: T[]): U[] => {
return arr.map((val) => f(val));
}
Run Code Online (Sandbox Code Playgroud)
当我map
使用匿名函数作为回调调用时,它的返回类型是正确的:
// `x1` variable type here is { name: string }[], which is correct
const x1 = map(x => x, [{name: 'John'}]);
Run Code Online (Sandbox Code Playgroud)
但是当我提供identity
函数而不是匿名函数时,返回类型是错误的:
const identity = <T>(x: T) => x
// return type of `x2` is {}[] here
const x2 = map(identity, [{name: 'John'}]);
Run Code Online (Sandbox Code Playgroud)
如何为第二个例子获得正确的类型结果,而不为map
函数提供显式类型参数?
经过一番尝试后,我真的怀疑 TypeScript 能否跟得上你那么远。例如:
const x4 = map(identity, [2]);
// x4 is '{}[]'
Run Code Online (Sandbox Code Playgroud)
这显然比你的例子更错误。
其他一些测试:
const x2 = map(<({ name: string }) => { name: string }>identity, [{ name: 'John' }]);
// x2 is '{ name: string }[]'
Run Code Online (Sandbox Code Playgroud)
和:
const double = (x: number) => 2 * x;
const x3 = map(double, [2]);
// x3 is 'number[]'
Run Code Online (Sandbox Code Playgroud)
这让我得出结论,TypeScript 无法将所有泛型分解为有意义的类型,而只是表示{}。
归档时间: |
|
查看次数: |
223 次 |
最近记录: |