Declare dynamically added class properties in TypeScript

给你一囗甜甜゛ 提交于 2019-11-29 07:06:14

The problem is that you're adding the new properties at runtime and the compiler has no way of knowing that.

If you know the property names in advance then you can do this:

type Json = {
    foo: string;
    bar: string;
}

...

const myInstance = new MyClass(someJson) as MyClass & Json;
console.log(myInstance.foo) // no error

Edit

If you do not know the properties in advance then you can't do this:

console.log(myInstance.foo);

Because then you know that foo is part of the received json, you'll probably have something like:

let key = getKeySomehow();
console.log(myInstance[key]);

And this should work without an error from the compiler, the only problem with that is that the compiler doesn't know the type for the returned value, and it will be any.

So you can do this:

const myInstance = new MyClass(someJson) as MyClass & { [key: string]: string };
let foo = myInstance["foo"]; // type of foo is string
let someProperty = myInstance["someProperty"]; // type of someProperty is boolean

2nd edit

As you do know the props, but not in the class, you can do:

type ExtendedProperties<T> = { [P in keyof T]: T[P] };
function MyClassFactory<T>(json: string): MyClass & ExtendedProperties<T> {
    return new MyClass(json) as MyClass & ExtendedProperties<T>;
}

Then you simply use it like so:

type Json = {
    foo: string;
    bar: string;
};
const myInstance = MyClassFactory<Json>(someJson);

Note that this will work only on typescript 2.1 and above.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!