[英]Dynamic Typescript Object Properties from Function Arguments
I have a function that takes in a n number of arguments, and generates a new object containing a key-value map of the arguments to a unique hash. 我有一个函数,它接受n个参数,并生成一个新对象,其中包含唯一哈希参数的键值映射。
Is there a way for Typescript to dynamically infer the keys of the returned object from the arguments of the function? 有没有一种方法可以让Typescript从函数的参数中动态推断返回对象的键?
Example, 例,
CreateActionType function that generates the dictionary: 生成字典的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);
};
Using 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"
I would like to remove the duplication, and just call createActionType like: 我想删除重复,只需调用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
Found a solution using then in keyword 使用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 }>;
};
Using K as the arguments of the function, we can assign the return value to be an object with keys containing string literals defined by K. 使用K作为函数的参数,我们可以将返回值赋值为一个对象,其中包含由K定义的字符串文字的键。
Additional Reading: https://github.com/Microsoft/TypeScript/wiki/What's-new-in-TypeScript#mapped-types 附加阅读: https : //github.com/Microsoft/TypeScript/wiki/What's-new-in-TypeScript#mapped-types
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.