[英]How to specify typescript conditional type based on a function return type in the arguments
我有一個這樣的功能:
export const getValue = (
options: Options = { someMapping, someFunction }
): string | MyType => {
...
return someFunction({ ...someData });
};
現在,返回類型是字符串或MyType。
這是因為someFunction可以返回字符串或MyType。
有沒有一種方法可以使用TypeScript條件類型根據someFunction實際返回的內容返回正確的類型?
[第一篇文章后的其他信息] :
這是選項類型的定義:
export interface Options {
someMapping: MappingType;
someFunc: (data: MyType) => MyType | string;
}
someFunc參數是需要MyType參數的函數。
根據情況,我傳入了兩個實際函數:
const myFunc = (data: MyType): string => {
return data.someProperty;
};
const myFunc = (data: MyType): MyType => {
return data;
};
我認為最接近的方法是鍵入someFunction
並使用函數重載。 Options
使它稍微復雜一些,但是這樣的方法應該起作用:
type MyFunc<T extends MyType | string> = () => T;
interface Options<T extends MyType | string> {
someMapping: WhateverTypeThisIs;
someFunc: MyFunc<T>;
}
function getValue(options: Options<MyType>): MyType;
function getValue(options: Options<string>): string;
function getValue<T extends MyType | string>(options: Options<T>): T {
return options.someFunc();
}
所以現在您應該為以下內容輸入內容:
const myTypeOptions: Options<MyType> = {
someMapping: {},
someFunc: () => ({ myParam: "MyValue" })
};
const myStringOptions: Options<string> = {
someMapping: {},
someFunc: () => "Hello"
};
const myTypeValue = getValue(myOptions); // myNumberValue is of type { myParam: string };
const myStringValue = getValue(myStringOptions); // myStringValue is a string;
這當然取決於所討論的函數始終返回MyType
或始終返回string
的事實。 如果它根據函數的參數而變化,則它將始終是MyType | string
MyType | string
因為Typescript無法確定。 它將由調用者確定它是什么。
編輯:
根據您提出的方案,類似的方法可能會有所幫助。 您可以創建MyFunc
類型。
type MyTypeFunc = (myType: MyType) => MyType;
type MyStringFunc = (myType: MyType) => string;
interface MyOptions {
someMapping: WatheverTypeThisIs;
}
interface MyTypeOptions extends MyOptions {
someFunc: MyTypeFunc;
}
interface MyStringOptions extends MyOptions {
someFunc: MyStringFunc;
}
function getValue(options: MyTypeOptions): MyType;
function getValue(options: MyStringOptions): string;
function getValue(options: MyTypeOptions | MyStringOptions): T {
return options.someFunc();
}
現在,無論何時調用它,您都可以創建或類似以下的選項:
const myTypeOptions: MyTypeOptions = {
someMapping: {},
someFunc: (myType) => myType
}
const myStringOptions: MyStringOptions = {
someMapping: {},
someFunc: (myType) => myType.someProperty
}
const myTypeValue = getValue(myTypeOptions); // myTypeValue will be of type MyType
const myStringValue = getValue(myStringOptions); // myStringValue will be of type string
在Playground中,您可以讓Typescript推斷返回類型。 @DeeV提供的函數重載也可以。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.