简体   繁体   English

为类编写Typescript接口

[英]Writing Typescript interface for a 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. 从文档中,我知道可以使用接口来描述Class的“实例”端。 But how would you write the interface that describes the "static" side of the Class? 但是,您将如何编写描述类的“静态”方面的接口?

Here's an example: 这是一个例子:

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

class Person implements IPerson {
    public name: string;

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

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

In this example, how would you modify IPerson so that the constructor function can also be described as well? 在此示例中,您将如何修改IPerson以便也可以描述构造函数?

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

Static interface: 静态接口:

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

let p: IPersonStatic = Person;

Also, you can use typeof to determine the type: 另外,您可以使用typeof确定类型:

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

I added IPersonConstructor to your example. 我在您的示例中添加了IPersonConstructor The rest is identical; 其余的是相同的。 just included for clarity. 只是为了清楚起见包括在内。

new (arg1: typeOfArg1, ...): TypeOfInstance; describes a class, since it can be invoked with new and will return an instance of the class. 描述一个类,因为它可以用new调用,并返回该类的实例。

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

class Person implements IPerson {
    public name: string;

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

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

interface IPersonConstructor {
    // When invoked with `new` and passed a string, returns an instance of `Person`
    new (name: string): Person;
    prototype: Person;
}

How about a generic 泛型怎么样

interface IConstructor<T> extends Function {
    new (...args: any[]): T;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM