小编Prz*_*ert的帖子

TypeScript:使函数参数有条件可选

我希望只有在满足某些条件时才采用第二个参数的函数。

let fn  = <T extends boolean>(arg1: T, arg2: T extends true ? void : string) => {};

fn(true); // ERROR Expected 2 arguments, but got 1
fn(true, undefined); // OK
fn(false, ''); // OK
Run Code Online (Sandbox Code Playgroud)

这是很奇怪的行为,特别是因为类型函数参数作为 void 不会强制在调用中传递。例如:

let fn1 = (arg: void) => {};
fn1(); // OK
Run Code Online (Sandbox Code Playgroud)

操场

typescript typescript-generics typescript-typings

2
推荐指数
1
解决办法
922
查看次数