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.
Is there a way for Typescript to dynamically infer the keys of the returned object from the arguments of the function?
Example,
CreateActionType function that generates the dictionary:
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:
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:
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
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.
Additional Reading: https://github.com/Microsoft/TypeScript/wiki/What's-new-in-TypeScript#mapped-types
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With