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?
CodePudding user response:
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;
}
CodePudding user response:
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
}
