miso miso - 11 months ago 48
TypeScript Question

Instruct to typescript that a class assigns properties dinamically

I have a simple class definition like below:

class Model {
constructor(props?:{}) {
_extend(props, this);

Where the constructor accepts an object as argument and copies its properties to the instance with an
function defined somewhere.

My problem is that Typescript complains about properties that are not defined in the class definition when I try to access to then.

let model = new Model({id: 1, name: 'coyote'});
model.id; // Property 'id' does not exist on type Model

Is there a way to tell to TypeScript that this class in specific can have properties not defined in the class?

Currently I am accessing to the properties using the form
in my test files.

Answer Source

You may consider an alternative using factory method:

class Model {
    private constructor(props?: any) { }

    static create<T>(props?: T): T & Model {
        return new Model(props) as T & Model;

let model = Model.create({ a: 123 });