3

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

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.