wmock wmock - 5 months ago 32
Javascript Question

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?

Answer

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;