我有一个函数接受 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 关键字找到解决方案
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
关于javascript - 来自函数参数的动态 Typescript 对象属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43334089/