typescript - 静态类的 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.
在此处查看打字稿游乐场
解决方案
好的,所以我通过不再导出静态类来修复它。我把它变成了一个普通的类,我将它实例化并作为常量导出。
回答:
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];
推荐阅读
- javascript - 将服装快捷操作添加到 Tampermonkey 脚本中
- php - 带有 mysql 的 php:导入 .csv 分隔空间
- python - 最小路径总和中的 UnboundLocalError
- typescript - 如何在 TypeScript 构建中包含整个文件夹?
- angular - TS2564 属性 mapViewEl 没有初始化器
- python-3.x - 绘制多个同心三角形和极坐标图,圆圈内的圆圈
- assembly - NASM 简单引导加载程序不会使用 INT 13H 加载扇区
- node.js - 复制失败:尝试在 DigitalOcean Droplet 上的 Docker 中复制 package.json 文件时的状态
- flask - discord-oauth 和烧瓶(夸脱)set-cookie 失败
- c# - UWP: 0x80131040: 定位程序集的清单定义与程序集引用不匹配