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

后端 未结 3 773
南旧
南旧 2021-02-12 21:19

In React I can restrict a variable to subset of values, like

PropTypes.oneOf([\'Home\', \'About\']),

How do I do that in TypeScript?

3条回答
  •  梦毁少年i
    2021-02-12 21:45

    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;
    

提交回复
热议问题