【发布时间】:2018-07-13 22:29:20
【问题描述】:
TypeScript 2.8.4 处于严格模式
我有一个这样的枚举:
export enum TabIndex {
Editor = 'editor',
Console = 'console',
Settings = 'settings',
Outputs = 'outputs'
}
我正在创建这样的地图:
tabs = new Map(<[string, string][]>Object.keys(TabIndex).map((key: any) => [TabIndex[key], key]));
稍后,我尝试使用 Map 中应该可用的查询参数从该 Map 中获取特定成员:
const tabParam = this.urlSerializer.parse(this.location.path()).queryParams.tab; // this thign is either 'editor', 'console', 'settings', ... etc.
然后我做
if (this.tabs.has(tabParam)) { // at this point we know the tab is available
this.selectTab(TabIndex[this.tabs.get(tabParam)!]); // here, TS thinks the index may be undefined, that's why I'm using the non-null assertion operator "!"
}
这段代码仍然让 TS 不高兴。它出错了:
Element implicitly has an 'any' type because index expression is not of type 'number'.
确实,索引类型是字符串。但我知道这就是它应该的样子,因为枚举支持字符串值。有人知道如何在这里让 TS 开心吗?
我做了一些研究,this issue 评论建议使用keyof typeof 解决此问题:
const tabParam: keyof typeof TabIndex = this.urlSerializer.parse(this.location.path()).queryParams.tab;
这只会让 TypeScript 再次不开心:
Type 'string' is not assignable to type '"Editor" | "Console" | "Settings" | "Outputs"'
【问题讨论】:
标签: typescript typescript-typings