来自函数参数的动态Typescript对象属性
问题描述:
我有一个函数,它需要一个参数个数,并生成一个包含唯一散列参数的键值映射的新对象。来自函数参数的动态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
答
发现在关键字
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