Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript declaration: Merge a class and an interface

I have two models Model and its subclass ClientModel an ambient module. Now I want to declare a set of attributes of ClientModel from an interface so called Client. How can I do it? I can imagine something like this:

interface Client {
    name: string;
    email: string;
}

declare class ClientModel extends Model implements Client {
    // with name and email here without redeclare them
}
like image 390
Quang Linh Le Avatar asked Dec 06 '17 09:12

Quang Linh Le


1 Answers

You can use declaration merging. If the class and the interface are declared in the same namespace/module and have the same name, they will be merged into a single class type.

interface ClientModel {
    name: string;
    email: string;
}

class ClientModel extends Model  {
    m() {
        this.email //Valid 
    }
}

If you cannot change the interface or is declared in another namespace and you can't move it you can inherit from it in the merged interface:

interface Client {
    name: string;
    email: string;
}

interface ClientModel extends Client {}
class ClientModel extends Model  {
    m() {
        this.email //Valid 
    }
}
like image 189
Titian Cernicova-Dragomir Avatar answered Sep 23 '22 13:09

Titian Cernicova-Dragomir