我想将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)道具:[“一个”,“两个”] ---有效
(b)道具:[“一个”] ---有效
(c)道具:[“ one”,“ XYZ”] ---如果“ XYZ”不属于枚举,则无效
我不确定应该如何投射道具,使其仅与枚举值列表匹配。
任何帮助将不胜感激!
谢谢
答案 0 :(得分:0)
您可以尝试如下创建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