考虑以下函数。
public static convert<T, U>(t: T, conversion: ((toutput: T) => U) = ((t) => t)) {
return conversion(t);
}
Typescript 目前提示转换函数返回的 toutput 参数,这是默认参数:
Type 'T' is not assignable to type 'U'. 'U' could be instantiated with an arbitrary type which could be unrelated to 'T'.
我试图让 IDE 认识到,在给定默认参数的情况下,T 与 U 相同。
我的用例如下:
convert(1) // returns 1
convert(1, x => ({x})) // returns an object with { x : 1 }
有没有人知道有什么方法可以让编译器安静下来并能够正确创建上面的这个函数?
最佳答案
我认为你可以通过重载来实现这一点:
public static function convert<T>(t: T): T;
public static function convert<T, U>(t: T, conversion: (t: T) => U): U;
public static function convert<T, U>(t: T, conversion?: (t: T) => U) {
return conversion ? conversion(t) : t;
}
..
const foo = convert(1) // inferred type 1
const bar = convert(1, x => ({x})) // inferred type { x : number }
1
被扩展为 number
,因为隐式文字类型在返回值的上下文中被扩展(例如 x => ({x})
),这又导致 T
被推断为 number
。您可以通过显式键入第一个参数来避免这种情况:
const bar = convert(1 as 1, x => ({x})) // inferred type { x: 1 }
关于Typescript 从默认值推断泛型类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55169365/