In React I can restrict a variable to subset of values, like
PropTypes.oneOf(['Home', 'About']),
How do I do that in TypeScript?
PS: I am not using TypeScript with React.
PropTypes is a runtime type-checking tool for props in React applications. Since React 15.5, the PropTypes utility is available through the prop-types package. With PropTypes, you can define the types of props expected in a component, like stating whether props are required or optional.
Props are required in TypeScript Another difference to notice here is that, with TypeScript, all props required by default. In the prop-types package, all props are optional by default. To make a prop required, you will have to use . isRequired explicitly.
You can combine static strings (or any regular type) by defining a union type:
type SomeType = 'Home' | 'About';
Or within an interface:
interface SomeType { prop : 'Home' | 'About'; }
And of course you can combine other types as well:
type SomeType = string | boolean;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With