简体   繁体   English

用于静态类的TypeScript索引器

[英]TypeScript indexer for static class

Basically what I'm trying to do is getting a value from a static class. 基本上我要做的是从静态类中获取值。 Like this: 像这样:

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];

This wil return the error: 这将返回错误:

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

See typescript playground HERE 这里看到打字稿游乐场

OK, so I fixed it by not exporting the static class anymore. 好的,所以我通过不再导出静态类来修复它。 I made it a normal class that I instantiate and export as a constant. 我把它作为一个普通的类,我实例化并导出为常量。

ANSWER: 回答:

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];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM