如何修改此代碼以運行
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[]
uj5u.com熱心網友回復:
您可以將條件回傳型別與assertions 一起使用,如下所示:
TS游樂場
function say <T extends boolean = false>(value = false as T) {
return (value ? ['hello'] : 'hello') as T extends true ? string[] : string;
}
或者一個多載的函式簽名,像這樣:
TS游樂場
function say (value?: false): string;
function say (value: true): string[];
function say (value = false) {
return (value ? ['hello'] : 'hello') as unknown;
}
在這兩種情況下,使用false或隱式呼叫函式undefined將導致string,呼叫 withtrue將導致string[]:
say(); // string
say(false); // string
say(true); // string[]
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/405557.html
標籤:
