Kuan
Kuan

Reputation: 11389

Interface with constructor inside implement questoin

All:

I am pretty new to TypeScript, when I read TypeScript Handbook from its official site, there is one example:

Difference between static/instance side of class When working with classes and interfaces, it helps to keep in mind that a class has two types: the type of the static side and the type of the instance side. You may notice that if you create an interface with a construct signature and try to create a class that implements this interface you get an error:

interface ClockInterface {
    new (hour: number, minute: number);
}

class Clock implements ClockInterface  {
    currentTime: Date;
    constructor(h: number, m: number) { }
}

This is because when a class implements an interface, only the instance side of the class is checked. Since the constructor sits in the static side, it is not included in this check.

Instead, you would need to work with the 'static' side of the class directly. In this example, we work with the class directly:

interface ClockStatic {
    new (hour: number, minute: number);
}

class Clock  {
    currentTime: Date;
    constructor(h: number, m: number) { }
}

var cs: ClockStatic = Clock;
var newClock = new cs(7, 30);

I just can not make myself understand why the last part work:

var cs: ClockStatic = Clock;
var newClock = new cs(7, 30);

I thought that cs is a variable which is going to refer to an object with ClockStatic Type, but why it can access a class name? And I thought Clock type is irrelevant to ClockStatic, why it can be given to cs?

Thanks

Upvotes: 0

Views: 4167

Answers (1)

Ryan Cavanaugh
Ryan Cavanaugh

Reputation: 221392

I thought that cs is a variable which is going to refer to an object with ClockStatic Type

This is 100% correct.

but why it can access a class name?

There are not "class names" in TypeScript/JavaScript. A class is an object like any other. You can think of the declaration class Clock being similar to the declaration var Clock: ClockStatic.

And I thought Clock type is irrelevant to ClockStatic

The class (other name: constructor function) Clock has a type that is compatible with ClockStatic. The type Clock refers to the type you get when you instantiate that class.

why it can be given to cs?

The class Clock satisfies the requirements of ClockStatic because it has an appropriate construct signature.

Upvotes: 1

Related Questions