2015-12-03 39 views
0

所有:接口,具有構造函數中實現questoin

我非常新的打字稿,當我從它的官方網站閱讀打字稿手冊,有一個例子:

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

我只是不能讓自己明白爲什麼最後一部分工作:

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

我認爲cs是一個變量,它將引用ClockStatic類型的對象,但爲什麼它可以訪問類名?我認爲Clock類型與ClockStatic無關,爲什麼它可以提供給cs?

感謝

回答

1

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

這是100%正確的。

but why it can access a class name?

TypeScript/JavaScript中沒有「類名」。一個類是一個與其他類似的對象。您可以想到與聲明var Clock: ClockStatic類似的聲明class Clock

And I thought Clock type is irrelevant to ClockStatic

(其他名稱:構造函數Clock有一個類型是與ClockStatic兼容。 類型Clock指的是您在實例化該類時獲得的類型。

why it can be given to cs?

Clock滿足ClockStatic的要求,因爲它有一個適當的結構特徵。

+0

謝謝,雖然這可能需要一些時間讓我理解,但我想它改變了我的一些概念誤解。但是現在我不太明白的是「類Clock」,如果聲明一個類就像定義一個帶有類體的變量作爲該變量類型的結構,那麼「Clock」只是一個沒有任何實際對象引用的變量名,它怎麼能被賦予另一個變量?就像在JS中:var a; var b; b = a;這讓我很難理解 – Kuan

相關問題