Typescript 根据可选参数推断返回类型函数
是否可以定义f()以根据第二个可选参数值推断返回类型, 维护参数的顺序。用于根据参数类型轻松确定返回类型:Typescript 根据可选参数推断返回类型函数,typescript,Typescript,是否可以定义f()以根据第二个可选参数值推断返回类型, 维护参数的顺序。用于根据参数类型轻松确定返回类型: // Silly function that does nothing function f(a: number, b?: number[], c?: number): string | boolean { if (b === undefined) return false; b.push(a);
// Silly function that does nothing
function f(a: number, b?: number[], c?: number): string | boolean {
if (b === undefined)
return false;
b.push(a);
if (c) b.push(c);
return b.toString();
}
const boolTypeValue = f(5); // type: boolean | string
const boolTypeValue = f(5, undefined, 8); // type: boolean | string
const stringValue = f(9, [], 0); // type: boolean | string
如果您还希望能够传递number[]| undefined
值,则需要第三个重载:
function f(a: number, b?: undefined, c?: number): false;
function f(a: number, b: number[], c?: number): string;
function f(a: number, b?: number[], c?: number): string | false {
if (b === undefined)
return false;
b.push(a);
if (c) b.push(c);
return b.toString();
}
const boolTypeValue: boolean = f(5);
const boolTypeValue2: boolean = f(5, undefined, 8);
const stringTypeValue: string = f(9, [], 0);
您键入了
string[]
作为返回类型。您的意思是返回字符串数组吗?原因b.toString()
正在对数组进行转换,而不是对数字进行转换。我刚刚更正了它
function f(a: number, b?: number[], c?: number): string | false;
declare const possiblyUndefinedArray: number[] | undefined;
const boolOrStringTypeValue: string | false = f(9, possiblyUndefinedArray, 0);