【问题标题】:How to typecast enum values as an array in typescript's interface/types?如何在打字稿接口/类型中将枚举值类型转换为数组?
【发布时间】:2021-02-14 20:38:55
【问题描述】:

我想将 interface/types 属性的 prop 类型转换为与枚举值匹配的任何元素的数组。

enum X = {
"one" = 1,
"two" = 2,
"three" = 3,
// .... and so on
}

interface Y {
 prop: X[] // this array should always contains values from enum only, not necessarily all
}

(a) prop: ["one", "two"] --- 有效

(b) 属性:["one"] --- 有效

(c) prop: ["one", "XYZ"] --- 无效,如果 "XYZ" 不是枚举的一部分

我不确定我应该如何对我的 prop 进行类型转换,以便它只匹配枚举值列表。

任何帮助将不胜感激!!!

谢谢

【问题讨论】:

  • 您的枚举定义无效。 typescriptlang.org/play?#code/…
  • 枚举成员不能有数字名称.ts(2452)
  • 对不起,这是我的错,我已经纠正了。
  • 所以你想提取枚举键作为一种类型?

标签: typescript enums interface typescript-types


【解决方案1】:

您可以尝试创建interface,如下所示 -

var myList = Object.keys(X) as Array<keyof typeof X>;

interface Y {
  prop: typeof myList;
}

然后吹就是测试:

const test0: Y = { prop: ['one', 'two', 'three'] }; // Valid
const test1: Y = { prop: ['one', 'two'] }; // Valid
const test2: Y = { prop: ['one'] }; //Valid
const test3: Y = { prop: ['one', 'XYZ'] }; //Error
const test4: Y = { prop: ['Two', 'zz'] }; //Error

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-12-09
    • 1970-01-01
    • 2019-03-04
    • 1970-01-01
    • 2019-06-09
    • 2019-07-09
    • 2018-02-14
    • 1970-01-01
    相关资源
    最近更新 更多