首页 > 解决方案 > 静态类的 TypeScript 索引器

问题描述

基本上我想做的是从静态类中获取一个值。像这样:

export enum Test {
    A = 10,
    B = 20,
    C = 30

}

export class TestObject
{
    constructor(public ValueA: string, public ValueB: Date){}
}

export class TestValues {
    [key: number] : TestObject;
    public static 10: TestObject = new TestObject ('AAA', new Date());
    public static 20: TestObject = new TestObject ('BBB', new Date());
    public static 30: TestObject = new TestObject ('CCC', new Date());
}

var a = Test.A as number;
var result = TestValues[a];

这将返回错误:

Element implicitly has an 'any' type because
type 'typeof TestValues' has no index signature.

在此处查看打字稿游乐场

标签: typescriptstaticindexer

解决方案


好的,所以我通过不再导出静态类来修复它。我把它变成了一个普通的类,我将它实例化并作为常量导出。

回答:

export enum Test {
    A = 10,
    B = 20,
    C = 30

}

export class TestObject
{
    constructor(public ValueA: string, public ValueB: Date){}
}

class TestValuesDefinition {
    [key: number] : TestObject;
    public 10: TestObject = new TestObject ('AAA', new Date());
    public 20: TestObject = new TestObject ('BBB', new Date());
    public 30: TestObject = new TestObject ('CCC', new Date());
}

export const TestValues = new TestValuesDefinition();

// And than in the other file
var a = Test.A;
var result = TestValues[a];

推荐阅读