简体   繁体   中英

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. 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?

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:

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

I added IPersonConstructor to your example. 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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