Typescript Passing prop as one of the objects's keys - values
I am using react native and trying to pass one of string values to another component.
The type
object looks like this:
export const ScannerAction = {
move: 'move',
inventory: 'inventory',
demand: 'demand',
supply: 'supply'
};
so when I pass a value called operationType
I want it to be one of the strings: move
, inventory
, demand
or supply
.
the child component would have an interface like this:
interface IIProps {
id: string;
otherStuff: any;
operationType: should be the type of ScannerAction
}
I could use
operationType: 'supply' | 'demand' | 'inventory' | 'move'
but I want it to be dynamic and editable only in one place. What should I do?
Solution 1:
The best way would be to use an enum instead of an object:
enum ScannerAction {
move = 'move',
inventory = 'inventory',
demand = 'demand',
supply = 'supply'
};
interface IIProps {
id: string;
otherStuff: any;
operationType: ScannerAction
}
If you want to stick to an object, you can use keyof
to get the keys and then get the values:
const ScannerAction = {
move: 'move',
inventory: 'inventory',
demand: 'demand',
supply: 'supply'
} as const; // make this const so that ScannerActionValues becomes a union of all values instead of string
type ScannerActionValues = typeof ScannerAction[keyof typeof ScannerAction];
interface IIProps {
id: string;
otherStuff: any;
operationType: ScannerActionValues;
}
Solution 2:
What about to use enum? https://www.typescriptlang.org/docs/handbook/enums.html
export enum ScannerAction {
move = 'move',
inventory = 'inventory',
demand = 'demand',
supply = 'supply'
}
interface usage:
interface IIProps {
id: string;
otherStuff: any;
operationType: ScannerAction
}