One of my functions takes in a variable number of arguments and creates a new object with a unique hash for each argument.
Can Typescript automatically determine the keys of the resulting object based on the function's arguments?
For instance,
I have a function called createActionType that builds a 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 want to simplify the process and just make a call to createActionType like this:
const action = createActionType("MY_ACTION_1", "MY_ACTION_2");
action.MY_ACTION_1; // Intellisense will recognize the properties MY_ACTION_1 and MY_ACTION_2 in action