问题
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
}
回答1:
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
}
}
来源:https://stackoverflow.com/questions/47670959/typescript-declaration-merge-a-class-and-an-interface