【发布时间】:2020-10-10 21:19:55
【问题描述】:
在 TypeScript 中,我有一个接受带有约束的泛型参数的函数:
function f1<U extends string>(param: U): U {
return param;
}
const a1 = f1('hello');
// a1's type is 'hello' -- Great!
现在,我正在尝试制作它,以便您可以选择添加另一种类型作为返回类型的一部分。但是,当我这样做时,我必须为 U 类型提供一个默认参数。这使得 TypeScript 停止推断 U 的值并使用我提供的默认类型:
function f2<T = never, U extends string = string>(param: U): U | T {
return param;
}
const b1 = f2('hello');
// b1's type is 'hello' -- Great!
const b2 = f2<boolean>('hello');
// b2's type is string | boolean -- Terrible: I want the type to be 'hello' | boolean.
const b3 = f2<boolean, 'hello'>('hello');
// b3's type is 'hello' | boolean -- Poor: The type is correct but API is redundant.
所以我的问题是,有没有办法让 TypeScript 继续从参数推断类型?我不想为 U 提供默认类型,我总是希望 TypeScript 推断出该值。显示我想要的完整 API 的伪代码:
function f3<T = never, U extends string = infer>(param: U): U | T {
return param;
}
const c1 = f3('hello');
// c1's type is 'hello' -- Great!
const c2 = f3<boolean>('hello');
// c2's type is 'hello' | boolean -- Great!
【问题讨论】:
标签: typescript typescript-generics