我正在构建一个TypeScript模块,该模块将函数导出给可以接受任意字符串输入的用户。我想解析这个输入以产生一个Enum值(如果输入不是一个有效的Enum值,则返回。)我希望这能用于字符串和数字枚举。
我该怎么做?这就是我所拥有的:
enum Foo { A = "A", B = "B" };
enum Bar { A = 0, B };
// Desired Foo[], got any[]
const allFoos = Object.keys(Foo).map(k => Foo[k]);
// Desired Bar[], got any[]
const allBars =
Object.keys(Bar)
.filter(k => typeof Bar[k] === "number")
.map(k => Bar[k]);
function parseFoo(arg: string): Foo {
if (allFoos.indexOf(arg) === -1) return;
return arg; // TypeScript should know arg is of type Foo by now.
}
function parseBar(arg: string): Bar {
if (allBars.indexOf(arg) === -1) return;
return arg; // TypeScript should know arg is of type Bar by now.
}
这是一个TypeScript游乐场链接:
答案 0 :(得分:1)
我要为枚举值构建枚举键映射:
const allFoos = mapKeys<Foo>(Foo);
const allBars = mapKeys<Bar>(Bar);
function mapKeys<T>(enumType: { [key: string]: any }) {
return Object.keys(enumType)
.filter(k => typeof enumType[k] === "string")
.reduce((map, key) => {
map.set(key, enumType[key]);
return map;
}, new Map<string, T>())
}
function parseFoo(arg: string): Foo {
return allFoos.get(arg);
}
function parseBar(arg: string): Bar {
return allBars.get(arg);
}
答案 1 :(得分:0)
这有帮助吗?
function parseFoo(arg: string): Foo {
if (allFoos.indexOf(arg) === -1) return;
return arg as Foo;
}
function parseBar(arg: string): Bar {
const argNum = Number(arg);
if (isNaN(argNum) || allBars.indexOf(argNum) === -1) return;
return argNum as Bar;
}