【发布时间】:2018-08-12 00:44:34
【问题描述】:
我正在构建一个 TypeScript 模块,该模块将函数导出给可以接受任意字符串输入的用户。我想解析这个输入以产生一个枚举值(如果输入不是有效的枚举值,则返回。)我希望它适用于字符串和数字枚举。
我该怎么做?这是我所拥有的:
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 游乐场链接:
【问题讨论】:
标签: typescript