Reputation: 165
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
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;
}
Upvotes: 1