在 class 上打字动态 属性

TypeScript dynamic property type on class

如果 class 属性 运算符访问动态 class 属性 类型,则有一种方法可以声明它的类型,如下例所示:

class Foo {
  [key: string]: number;
}

let a = new Foo();
let b = a['bar']; //Here, the compiler knows that b is a number

但是有没有一种方法可以在没有 [] 运算符的情况下声明同样的东西? 一种写法:

let a = new Foo();
let b = a.someProperty;

让 TypeScript 知道 somePropertynumber 类型,因为我们对它说:Foo 上的所有未知属性都是数字.

我认为这是不可能的。当您定义 class 时,您定义了有关其属性和方法的 'static' 信息。如果您指定索引器 - 这意味着 - class 的对象将具有索引器,而不是任何属性。毕竟,这就是 classes 的用途 - 定义您的业务实体的结构。

我知道做与您想要的类似的事情的唯一方法是使用对象文字。例如,这将起作用:

let x: { PropA: number, [x: string]: number };
x = { PropA: 1, PropX: 2, PropY: 3, PropZ: 4 };

希望对您有所帮助。