TypeScript枚举值作为类型化数组

时间:2020-03-26 02:52:37

标签: typescript typescript-typings

试图像枚举类型那样在数组中键入可能的值:

enum MyEnum {
    FirstRole = "FIRST",
    SecondRole = "SECOND"
}

type MyType {
   roles: MyEnum[] // I want to enforce this array to only strings of FIRST or SECOND as depicted in the enum i.e. ["FIRST", "SECOND"]

2 个答案:

答案 0 :(得分:0)

您可以使用以下自定义类型简单地声明数组:

type Role =  "First" | "Second";
let roles: Array<Role> = [ "First"];

角色将仅允许第一或第二个字符串。

答案 1 :(得分:0)

就是这样

    enum MyEnum {
        FirstRole = 'FIRST',
        SecondRole = 'SECOND',
    }
    type role = 'FIRST' | 'SECOND';
    const role: MyEnum[] | role[] = [MyEnum.FirstRole, 'FIRST'];