我有一个接收 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
答案 0 :(得分: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