打字稿对象型怪语法

打字稿对象型怪语法

问题描述:

当读取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

它称为类型断言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

这是“铸造”。基本上将下列事物({},不带字段的对象字面量)解释为Square。因此,由于使用square将被TypeScript编译器推断为Square,Intellisense将显示正确的成员。

当然,它不是真正的“铸造”,因为我们知道类型只是TypeScript中的幻觉。这全都是编译器。