Auston Barboza
Auston Barboza

Reputation: 165

How to map each type of properties in object to a property in interface?

I am trying to create a dispatch action interface for a react-redux project in typescript. I would like to be able to decide type property in action interface based on another object which has all types that can be dispatched.

input:

const FooActions = {
    REMOVE_FOO: "removeFOO",
    ADD_FOO: "addFOO",
    UPDATE_FOO: "updateFOO",
};

interface FooActionType {
    type: "MAP ALL property values from FooActions";
    payload: any;
}

expected output:

interface FooActionType {
    type: "removeFOO" | "addFOO" | "updateFOO";
    payload: any;
}

Upvotes: 1

Views: 919

Answers (1)

Titian Cernicova-Dragomir
Titian Cernicova-Dragomir

Reputation: 249656

To get the types of a the values in an object you can use T[keyof T] (with T being the type). To preserve string literal types in FooActions you will need to use a type assertion.

Given the above it is simple to create FooActionType:


const FooActions = {
    REMOVE_FOO: "removeFOO",
    ADD_FOO: "addFOO",
    UPDATE_FOO: "updateFOO",
} as const;

interface FooActionType {
    type: typeof FooActions[keyof typeof FooActions];
    payload: any;
}

Play

Upvotes: 1

Related Questions