Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
466 views
in Technique[技术] by (71.8m points)

javascript - Difference between the static and instance sides of classes

I am trying to understand interface topic in Typescript when I came across Class type, I got this code from official docs

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

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

I can understand that Clock has no match for the signature new (hour: number, minute: number); that's why we get an error there.

But in docs the explaination is something which I am unable to understand. It goes in this way :

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.

Any explanation would be appreciated.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The interface declares the method/members that the instances have, and not what the implementing class has.

For example check the Array and ArrayConstructor declarations:

interface Array<T> {
    length: number;
    toString(): string;
    toLocaleString(): string;
    push(...items: T[]): number;
    pop(): T | undefined;
    ...
    [n: number]: T;
}

interface ArrayConstructor {
    new (arrayLength?: number): any[];
    new <T>(arrayLength: number): T[];
    new <T>(...items: T[]): T[];
    (arrayLength?: number): any[];
    <T>(arrayLength: number): T[];
    <T>(...items: T[]): T[];
    isArray(arg: any): arg is Array<any>;
    readonly prototype: Array<any>;
}

As you can see, the Array has method/members which exist on any instance of array:

let a = [];
a.push(1, 2, 3);
console.log(a.length);

But the ArrayConstructor has the members/methods which exist on the Array itself:

console.log(Array. prototype);
console.log(Array.isArray(9));

The constructors are part of the "static" part which is why they are declared in the ArrayConstructor.
If you declare a constructor on an interface for example you'll have a problem implementing that interface:

interface MyInterface {
    constructor();
    getName(): string;
}

class MyClass implements MyInterface {
    constructor() {}

    getName() { return "name" };
}

Error:

Class 'MyClass' incorrectly implements interface 'MyInterface'. Types of property 'constructor' are incompatible. Type 'Function' is not assignable to type '() => void'. Type 'Function' provides no match for the signature '(): any'.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...