我知道Typescript会自动推断输出是否为数组,但是我试图弄清楚如何使用条件类型显式设置它。
我已经尝试了以下类似方法,但似乎没有用。
function test<T>(...args:any[]): T extends any[] ? any[] : any {
// If there is only 1 arg, return a string
if(args.length === 1)
return 1;
// If there is more than 1 args, return an array
else
return [1,2,3]
}
有人知道我在做什么错吗?
答案 0 :(得分:1)
它给出的错误(2322)与使用以下代码得到的错误相同:
function example<T>(x: number | string): T {
if (typeof x === "number") {
return x * 2;
}
return x + x;
}
类型“数字”不可分配给类型“ T”。 可以用与“数字”无关的任意类型实例化“ T”。 (2322)
这就是说我可以编写如下代码:
example<object>(42);
...然后T
是object
,但是number
和string
都不能分配给object
。
您的test
函数也是如此。
我认为您只是在试验条件类型,但是只是为了完整性,就像您说的那样,TypeScript编译器可以推断出这些返回值,但是在特定情况下,union type会推断出1 | number[]
。如果您想告诉TypeScript,带有一个参数的test
返回number
,带有多个参数的test
返回number[]
,则可以使用函数重载来实现:>
function test(x: any): number;
function test(x: any, y: any, ...more: any[]): number[];
function test(...args:any[]): number | number[] {
// If there is only 1 arg, return a string
if(args.length === 1)
return 1;
// If there is more than 1 args, return an array
else
return [1,2,3]
}
const x = test(1); // type of `x` is `number`
const y = test(1, 2, 3); // type of `y` is `number[]`