Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the TypeScript equivalent of "PropTypes.oneOf" (restrict a variable to subset of values)

Tags:

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.

like image 506
aWebDeveloper Avatar asked May 09 '18 08:05

aWebDeveloper


People also ask

What is PropTypes in TypeScript?

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.

Is PropTypes necessary in TypeScript?

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.


1 Answers

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; 
like image 123
lumio Avatar answered Sep 18 '22 22:09

lumio