打字稿:在类上动态分配属性

Dan*_*son 7 typescript

我有一个类将变量数据绑定到它的实例上.

class RouteData{
  constructor(data: Object) {
    // binding object attributes to instance
    Object.keys(data).forEach((key) => { this[key] = data[key];})
  }
}

let route: RouteData = new RouteData({hello: "test"})
console.log(route.hello);
Run Code Online (Sandbox Code Playgroud)

以上的结果是test.

但是,我在编译时遇到错误.

example.ts(9,19): error TS2339: Property 'hello' does not exist on type 'RouteData'.

如何声明此类的类型以允许绑定其类上的任何属性.

小智 7

之前添加一个演员.

console.log((<any>route).hello);
Run Code Online (Sandbox Code Playgroud)