如何使泛型和默认值一起工作
How to make generics and default value work together
如何将此代码修改为 运行
function say<T = boolean>(arg:T = false) {
// ^^^^^^^^^^^^^ Could be instantiated with an arbitrary type which could be unrelated to
if(arg) return ['hello']
return 'hello'
}
const a = say() //type is string
const b = say(true) //type is string[]
您可以使用 conditional return type with assertions,像这样:
function say <T extends boolean = false>(value = false as T) {
return (value ? ['hello'] : 'hello') as T extends true ? string[] : string;
}
或者一个重载的函数签名,像这样:
function say (value?: false): string;
function say (value: true): string[];
function say (value = false) {
return (value ? ['hello'] : 'hello') as unknown;
}
在这两种情况下,使用 false
或隐式 undefined
调用函数将导致 string
,使用 true
调用将导致 string[]
:
say(); // string
say(false); // string
say(true); // string[]
如何将此代码修改为 运行
function say<T = boolean>(arg:T = false) {
// ^^^^^^^^^^^^^ Could be instantiated with an arbitrary type which could be unrelated to
if(arg) return ['hello']
return 'hello'
}
const a = say() //type is string
const b = say(true) //type is string[]
您可以使用 conditional return type with assertions,像这样:
function say <T extends boolean = false>(value = false as T) {
return (value ? ['hello'] : 'hello') as T extends true ? string[] : string;
}
或者一个重载的函数签名,像这样:
function say (value?: false): string;
function say (value: true): string[];
function say (value = false) {
return (value ? ['hello'] : 'hello') as unknown;
}
在这两种情况下,使用 false
或隐式 undefined
调用函数将导致 string
,使用 true
调用将导致 string[]
:
say(); // string
say(false); // string
say(true); // string[]