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

后端 未结 3 777
南旧
南旧 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条回答
  •  栀梦
    栀梦 (楼主)
    2021-02-12 21:42

    Only one type among several one is a union type, and in your case a union of string literal.

    You can convert an array of string literals into a union of string literals as follow:

    If you do have a const array or string you can define a type:

    const menuList = ["Home", "About"] as const;
    type menuName = typeof menuList[number] // "Home" | "About"
    

    If you do already have a type with the array just do:

    type menuList = ["Home", "About"];
    type menuItem = menuList[number] // "Home" | "About"
    

提交回复
热议问题