[英]Typescript function return type based on parameter properties
如何為 function 創建正確的類型,以便根據其輸入參數的屬性,在調用此 function 時獲得正確的返回類型?
這是我目前得到的,但兩個電話都給我相同的boolean | boolean[]
boolean | boolean[]
當fn({ a: 42 })
應該給我boolean
和fn({ b: 'hi' })
應該給我boolean[]
時鍵入。
type ParamType = { a?: number, b?: string }
type ReturnType<T> =
T extends 'a' ? boolean :
T extends 'b' ? boolean[] :
never[]
function fn<T extends keyof ParamType>(arg: ParamType) {
if (arg.a) {
return true as ReturnType<T>;
}
else if (arg.b) {
return [true, false] as ReturnType<T>;
}
else return [] as ReturnType<T>;
}
fn({ a: 42 }); // function fn<"a" | "b">(arg: ParamType ): boolean | boolean[]
fn({ b: 'hi' }); // function fn<"a" | "b">(arg: ParamType ): boolean | boolean[]
此外,我不太喜歡在類型中定義文字 object 屬性a
和b
兩次,如果有更好的方法,請指出正確的方向。
您的問題很不尋常,但首先:使用in
operator 來檢查密鑰是否存在。 其次:如果 a 和 b 都被聲明,這沒有效果,即使是可選的。 使用聯合。 最后,如果你聲明了一個沒有賦值給參數的類型參數,在大多數情況下,它是沒有效果的。
試試這個:
type ParamType = {a: number | string;} | {b: number | string;};
type MyReturnType<T> =
T extends 'a' ? boolean :
T extends 'b' ? boolean[] :
never[];
function fn<T extends ParamType>(arg: T) {
if ("a" in arg) {
return true as MyReturnType<keyof T>;
}
else if ("b" in arg) {
return [true, false] as MyReturnType<keyof T>;
}
else return [] as MyReturnType<keyof T>;
}
fn({a: 42});
/*function fn<{
a: number;
}>(arg: {
a: number;
}): boolean*/
fn({b: 'hi'});
/*function fn<{
b: string;
}>(arg: {
b: string;
}): boolean[]*/
請參閱https://www.typescriptlang.org/docs/handbook/typescript-in-5-minutes-func.html#unions和https://www.typescriptlang.org/docs/handbook/release-notes/類型保護的 typescript-2-7.html#type-guards-inferred-from-in-operator in
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.