打字稿声明:合并一个类和一个接口 [英] Typescript declaration: Merge a class and an interface

查看:96
本文介绍了打字稿声明:合并一个类和一个接口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个模型Model及其子类ClientModel环境模块.现在,我想从所谓的Client接口声明一组ClientModel属性.我该怎么做?我可以想象这样的事情:

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
}

推荐答案

您可以使用声明合并.如果类和接口在相同的名称空间/模块中声明并且具有相同的名称,则它们将被合并为单个类类型.

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

这篇关于打字稿声明:合并一个类和一个接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆