[英]Dynamic Typescript Object Properties from Function Arguments
我有一個函數,它接受n個參數,並生成一個新對象,其中包含唯一哈希參數的鍵值映射。
有沒有一種方法可以讓Typescript從函數的參數中動態推斷返回對象的鍵?
例,
生成字典的CreateActionType函數:
function createActionType<K extends {} | void>(...type: string[]): Readonly<{ [key: string]: string }> {
const actions = {};
type.forEach((item: string) => {
actions[item] = `${item}/${generateUniqueId()}`;
});
return Object.freeze(actions);
};
使用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
使用then in keyword找到解決方案
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.