简体   繁体   English

打字稿对象奇怪的类型语法

[英]typescript object strange type syntax

When reading TypeScript handbook , I came across following example: 在阅读TypeScript手册时 ,我遇到了以下示例:

interface Shape {
    color: string;
}

interface Square extends Shape {
    sideLength: number;
}

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

The question is - what is actually <Square>{} ? 问题是-什么是<Square>{} Seems like a bizarre syntax to me. 对我来说似乎是一种奇怪的语法。 From Java/C# point of view, it's like a generic of an anonymous object. 从Java / C#的角度来看,它就像一个匿名对象的泛型。 What exactly is it and what are the limitations of such creation? 它到底是什么?这种创作的局限性是什么?

It's "casting". 这是“广播”。 Interpret the following thing ( {} , an object literal with no fields) as a Square basically. 基本上将以下内容( {} ,没有字段的对象文字)解释为Square So because of the usage of that the square will be inferred to be of type Square by the TypeScript compiler and Intellisense will show the correct members. 所以,因为那的使用square将被推断为类型的Square由打字稿编译器和智能感知会显示正确的成员。

Of course it's not real "casting", as we know types are just an illusion in TypeScript. 当然,这不是真正的“广播”,因为我们知道类型只是TypeScript中的一种幻觉。 It's all for the compiler. 全部用于编译器。

Its called a Type Assertion https://basarat.gitbooks.io/typescript/content/docs/types/type-assertion.html 它称为类型断言https://basarat.gitbooks.io/typescript/content/docs/types/type-assertion.html

And the pattern you are looking at: 您正在查看的模式:

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

Is common (but not recommended) for JS -> TS Migration for lazy object initialization : https://basarat.gitbooks.io/typescript/content/docs/tips/lazyObjectLiteralInitialization.html 对于JS-> TS迁移(对于惰性对象初始化)是常见的(但不推荐): https : //basarat.gitbooks.io/typescript/content/docs/tips/lazyObjectLiteralInitialization.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM