2017-04-10 77 views
2

我有一個函數,它需要一個參數個數,並生成一個包含唯一散列參數的鍵值映射的新對象。來自函數參數的動態Typescript對象屬性

有沒有一種方法讓Typescript能夠從函數的參數中動態地推斷返回對象的鍵?


例,

生成字典

CreateActionType功能:

​​

使用createActionType:

interface ActionTypes { 
    MY_ACTION_1, 
    MY_ACTION_2 
} 

const action = createActionType<ActionTypes>("MY_ACTION_1", "MY_ACTION_2"); 
/* 
* action contains { MY_ACTION_1: "MY_ACTION_1/0", MY_ACTION_2: "MY_ACTION_2/1" } 
*/ 
action.MY_ACTION_1; // returns "MY_ACTION_1/0" 

我想刪除的重複數據刪除,並調用createActionType像:

const action = createActionType("MY_ACTION_1", "MY_ACTION_2"); 
action.MY_ACTION_1; // Intellisense will be able to infer the properties 
        // MY_ACTION_1 and MY_ACTION_2 from action 

回答

2

發現在關鍵字

function createActionType<K extends string>(...type: K[]): { [P in K]: string } { 
    const actions = {}; 

    type.forEach((item: string) => { 
     actions[item] = `${item}/${generateUniqueId()}`; 
    }); 

    return Object.freeze(actions) as Readonly<{ [P in K]: string }>; 
}; 

使用K作爲函數的自變量使用然後一個解決方案,我們可以分配的返回值是與由K.

定義包含字符串文字鍵的對象

附加閱讀:https://github.com/Microsoft/TypeScript/wiki/What's-new-in-TypeScript#mapped-types