2016-02-04 95 views
1

當讀取TypeScript handbook,我碰到下面的例子就是:打字稿對象型怪語法

interface Shape { 
    color: string; 
} 

interface Square extends Shape { 
    sideLength: number; 
} 

var square = <Square>{}; 
square.color = "blue"; 
square.sideLength = 10; 

的問題是 - 什麼是真正的<Square>{}?對我來說似乎是一種奇怪的語法。從Java/C#的角度來看,它就像一個匿名對象的泛型一樣。究竟是什麼,這種創造的侷限性是什麼?

+0

這看起來像一個鑄造 – SLaks

回答

3

它稱爲類型斷言https://basarat.gitbooks.io/typescript/content/docs/types/type-assertion.html

你正在尋找的模式:(推薦但不是)

var square = <Square>{}; 
square.color = "blue"; 
square.sideLength = 10; 

是很常見的JS - > TS移民懶惰對象初始化:https://basarat.gitbooks.io/typescript/content/docs/tips/lazyObjectLiteralInitialization.html

+0

omg,甚至這樣的東西都在你的書中!是否值得閱讀官方的TS手冊,或者我只是跳到你的書:)? – ducin

4

這是「鑄造」。基本上將下列事物({},不帶字段的對象字面量)解釋爲Square。因此,由於使用square將被TypeScript編譯器推斷爲Square,Intellisense將顯示正確的成員。

當然,它不是真正的「鑄造」,因爲我們知道類型只是TypeScript中的幻覺。這全都是編譯器。