Skip to content Skip to sidebar Skip to footer

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 a

Solution 1:

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;

Solution 2:

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

Solution 3:

How about a generic

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

Post a Comment for "Writing Typescript Interface For A Class"