如果函数有重载,标准 TypeScript
Parameters<T>
帮助器仅返回最后版本参数的类型。有办法绕过这个限制吗?
type StringNumber = `${number}`;
function add(a: StringNumber, b: StringNumber): number
function add(a: number, b: number): number
function add<T extends (StringNumber | number)>(a: T, b: T): number
{
return Number(a) + Number(b);
}
type AddParameters = Parameters<typeof add> // => [a: number, b: number]
const addParams: AddParameters = ['1', '3']; // Error
您可以手动指定每个重载的类型。然后在重载中使用它。
type StringNumber = `${number}`;
type ParamsStringNumber = [a: StringNumber, b: StringNumber];
type ParamsNumber = [a: number, b: number];
function add(...params: ParamsStringNumber): number
function add(...params: ParamsNumber): number
function add<T extends (StringNumber | number)>(a: T, b: T): number
{
return Number(a) + Number(b);
}
type AddParameters = ParamsStringNumber | ParamsNumber;
const addParams: AddParameters = ['1', '3'] as AddParameters; // no error
type StringNumber = `${number}`;
type StringNumberOrNumber = StringNumber | number
function add(a: StringNumberOrNumber, b: StringNumberOrNumber): number
{
return Number(a) + Number(b);
}
// Examples
add(1, 2) // OK
add("1", "2") // OK
add("1", 2) // OK
add(1, "2") // OK
add(null, 1) // error (a)
add(1, null) // error (b)
add("a", 2) // error (a)
add(1, "a") // error (b)