Skip to content Skip to sidebar Skip to footer

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. Is there a way for Typescript to d

Solution 1:

Found a solution using then in keyword

function createActionType<K extendsstring>(...type: K[]): { [P in K]: string } {
    const actions = {};

    type.forEach((item: string) => {
        actions[item] = `${item}/${generateUniqueId()}`;
    });

    returnObject.freeze(actions) asReadonly<{ [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

Post a Comment for "Dynamic Typescript Object Properties From Function Arguments"