簡體   English   中英

使用映射類型返回函數返回類型的對象

[英]Using mapped types to return object of return types of functions

我有一個函數,它將一個對象作為參數並返回一個新對象。 對象參數將是返回任意類型的函數的對象,而我函數的返回類型將是與對象參數具有相同鍵的對象,但是值將是對象參數中各個鍵的返回類型。

現在要抓住的是,來自object參數的函數可能會引發錯誤,我不想在流程的中間中斷執行,而是收集所有失敗的鍵,然后引發自己的自定義錯誤。

這是我到目前為止的內容:

type ObjectParamFn =  <T>(...arbitrary: any[]) => T | never;
type ObjectParam = { [key: string]: ObjectParamFn };
type MyMethodReturnType<T extends ObjectParam> = {
    [P in keyof T]: ReturnType<T[P]>;
}

function myMethod<T extends ObjectParam>(
    param: T
): MyMethodReturnType<T> | never {
    const returnValue = {} as MyMethodReturnType<T>;
    const errors = [];
    for (let propName in param) {
        if (param.hasOwnProperty(propName)) {
            try {
                const value = param[propName](/* arbitrary */);
                returnValue[propName] = value; // TS ERROR HERE: Type '{}' is not assignable to type 'ReturnType<T[Extract<keyof T, string>]>'.
            } catch (err) {
                errors.push(propName);
            }
        }
    }

    if (errors.length) {
        throw new Error('foo');
    }

    return returnValue;
}

我標記了我收到的TS錯誤的位置,但將其分成自己的一行:

Type '{}' is not assignable to type 'ReturnType<T[Extract<keyof T, string>]>'.

我覺得自己已經接近解決方案,但不能完全克服最后的困難。 任何幫助將不勝感激。

我可以通過消除ObjectParamFn的泛型來實現此目的,因為在我的代碼庫中,我實際上知道返回類型的類,因此我將其定義為一個並從那里開始工作。

type Primitive = string | number | boolean | null;
type ObjectParamFn = (...arbitrary: any[]) => Primitive | never;
type ObjectParam = { [key: string]: ObjectParamFn };
type MyMethodReturnType<T extends ObjectParam> = {
    [P in keyof T]: ReturnType<T[P]>;
}

function myMethod<T extends ObjectParam>(
    param: T
): MyMethodReturnType<T> | never {
    let returnValue = {} as { [key: string]: any };
    const errors = [];
    for (let propName in param) {
        if (param.hasOwnProperty(propName)) {
            try {
                returnValue[propName] = param[propName]();
            } catch (err) {
                errors.push(propName);
            }
        }
    }

    if (errors.length) {
        throw new Error('foo');
    }

    return returnValue as MyReturnType<T>;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM