为类编写Typescript接口 [英] Writing Typescript interface for a Class

查看:147
本文介绍了为类编写Typescript接口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读《打字稿手册》的类类型部分,对于如何编写类的接口定义感到困惑.从文档中,我知道可以使用一个接口来描述Class的实例"端.但是,您将如何编写描述Class的静态"方面的接口?

I'm reading the Class Types section of the Typescript Handbook and I'm confused about how to write the interface definition for a Class. From the documentation, I understand that an interface can be used to describe the "instance" side of the Class. But how would you write the interface that describes the "static" side of the Class?

这是一个例子:

interface IPerson {
    name: string;
    getName(): string;
}

class Person implements IPerson {
    public name: string;

    constructor(name: string) {
        this.name = name;
    }

    public getName() {
        return this.name;
    }
}

在此示例中,您将如何修改IPerson,以便也可以描述构造函数?

In this example, how would you modify IPerson so that the constructor function can also be described as well?

推荐答案

您可以为您的静态需求创建一个单独的接口:

You can create a separate interface for your static needs:

interface IPerson {
    name: string;
    getName(): string;
}

class Person implements IPerson {
    public name: string;

    constructor(name: string) {
        this.name = name;
    }

    public getName() {
        return this.name;
    }

    public static create(name: string) { // method added for demonstration purposes
        return new Person(name);
    }
}

静态界面:

interface IPersonStatic {
    new(name: string); // constructor
    create(name: string): IPerson; // static method
}

let p: IPersonStatic = Person;

此外,您可以使用typeof确定类型:

Also, you can use typeof to determine the type:

let p2: typeof Person = Person; // same as 'let p2 = Person;'
let p3: typeof Person = AnotherPerson;

这篇关于为类编写Typescript接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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