TypeScript 3.1 : 如何在严格模式下使用枚举索引数组?



当由于"noImplicitAny"而启用TypeScript"严格"模式时,此代码不会编译。

你能告诉我如何声明/使用由枚举值索引的数组吗?

namespace CommandLineParser {
enum States { sNoWhere, sSwitchValue }
abstract class State {        
}
class NoWhereState extends State {
}
class SwitchValueState extends State {
}
export class GetOption {
state: State;
states: Array<State>[States];
constructor() {
this.states = new Array(2);
this.states[States.sNoWhere] = new NoWhereState();
this.states[States.sSwitchValue] = new SwitchValueState();
this.state = this.states[States.sNoWhere];
}
}
}
let go = new CommandLineParser.GetOption();

错误是:

错误 TS7017:元素隐式具有"any"类型,因为类型"State"没有索引签名。

this.states[States.sNoWhere] = new NoWhereState(this);
~~~~~~~~~~~~~~~~~~~~~~~~~~~~

错误 TS7017:元素隐式具有"any"类型,因为类型"State"没有索引签名。

this.states[States.sSwitchValue] = new SwitchValueState(this);
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

错误 TS7017:元素隐式具有"any"类型,因为类型"State"没有索引签名。

this.state = this.states[States.sNoWhere];
~~~~~~~~~~~~~~~~~~~~~~~~~~~~

我知道这有点旧,而不是 realli 回答问题,但我发现在您的情况下使用对象而不是数组的方法更直观。请考虑以下事项:

enum MyIndexingEnum { stateOne, stateTwo }
const someIndexedObject {
[MyIndexingEnum.stateOne]: { /* stuff */ }
[MyIndexingEnum.stateTwo]: { /* stuff */ }
}
/* Accessing stuff */
someIndexedObject[MyIndexingEnum.stateOne]

问题是states的类型。你定义了一个State数组,但随后你使用一个类型查询,其结果将是State。赋值this.states = new Array(2);成功,因为State类没有成员,因此数组在技术上满足类签名。

这将起作用:

export class GetOption {
state: State;
states: Array<State>;
constructor() {
this.states = new Array(2);
this.states[States.sNoWhere] = new NoWhereState();
this.states[States.sSwitchValue] = new SwitchValueState();
this.state = this.states[States.sNoWhere];
}
}

现在这确实意味着您可以通过任何数字索引到数组中,而不仅仅是局限于枚举的类型元素,这可能不是您想要的。如果你真的不需要数组方法,一个简单的对象可能会更好用,尽管你必须一次初始化它(或使用类型断言来使其适合this.states = {} as any(:

export class GetOption {
state: State;
states: Record<States, State>;
constructor() {
this.states = {
[States.sNoWhere]: new NoWhereState(),
[States.sSwitchValue] : new SwitchValueState()
}
this.state = this.states[States.sNoWhere];
this.state = this.states[10]; //error
}
}

元组类型也可以工作,因为枚举常量无论如何都对应于数字,如果需要,您将获得Array方法:

export class GetOption {
state: State;
states: [State, State];
constructor() {
this.states = [new NoWhereState, new SwitchValueState]
this.state = this.states[States.sNoWhere];
this.state = this.states[10]; //error
}
}

最新更新