Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a child class in TypeScript using parent static method?

I have two classes: Model and User. User extends the Model.

export Model {
  id: number;
  static fromData<T>(data: any): T {
    return Object.assign(new Model(), data);
  }
}

export User extends Model {
  name: string;
  sayHi(): string {
    return 'Hi, ' + this.name;
  }
}

The way I wanted to use it looks like this:

const currentUser = User.fromData(dataFromServer);
const message = currentUser.sayHi();

Method hi() doesn't work because I have created an instance of Model class.

How to use TypeScript generics to get an instance of derived class using base class static method?

I'm planning number of different entities with common.

I saw this answer but I don't know how to pass parameters into a static method in my case.

like image 281
zoonman Avatar asked May 15 '18 05:05

zoonman


People also ask

Can we use static method in child class?

If we call a static method by using the parent class object, the original static method will be called from the parent class. If we call a static method by using the child class object, the static method of the child class will be called.

Can we have same static method in parent and child class?

The answer is 'Yes'. We can have two or more static methods with the same name, but differences in input parameters. For example, consider the following Java program.

Can we call static method of parent class?

A static method is the one which you can call without instantiating the class. If you want to call a static method of the superclass, you can call it directly using the class name.


1 Answers

Since the static method is on the class itself we have access to the class constructor using this inside the static method, this is the class iself. If we constrain the this parameter to the static method to be a constructor returning T (this: new ()=> T ) we will get correct typing for the return value. The this parameter is just for the benefit of the typescript compiler, it will not actually be emitted to JS and you don't have to pass it explicitly:

export class Model {
    id: number;
    static fromData<T>(this: new () => T, data: any): T {
        return Object.assign(new this(), data);
    }
}

export class User extends Model {
    name: string;
    sayHi(): string {
        return 'Hi, ' + this.name;
    }
}

const currentUser = User.fromData({ id: 10, name: ""});
const message = currentUser.sayHi();

Playground link

like image 57
Titian Cernicova-Dragomir Avatar answered Oct 06 '22 08:10

Titian Cernicova-Dragomir