typescriptinheritancedeclarationambient

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
}

Solution

  • 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 
        }
    }