【问题标题】:typescript object strange type syntaxtypescript 对象奇怪的类型语法
【发布时间】:2016-05-14 18:01:58
【问题描述】:

在阅读TypeScript handbook 时,我遇到了以下示例:

interface Shape {
    color: string;
}

interface Square extends Shape {
    sideLength: number;
}

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

问题是 - 实际上&lt;Square&gt;{} 是什么?对我来说似乎是一个奇怪的语法。从 Java/C# 的角度来看,它就像一个匿名对象的泛型。它究竟是什么,这种创作的局限性是什么?

【问题讨论】:

  • 看起来像演员表

标签: javascript object syntax typescript


【解决方案1】:

这是“铸造”。基本上将以下内容({},一个没有字段的对象文字)解释为Square。因此,由于 square 的使用,TypeScript 编译器将推断为 Square 类型,并且 Intellisense 将显示正确的成员。

当然,这不是真正的“强制转换”,因为我们知道类型只是 TypeScript 中的一种幻觉。一切都是为了编译器。

【讨论】:

    【解决方案2】:

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

    【讨论】:

    • 天哪,你的书中也有这样的内容!是否值得阅读官方的 TS 手册,还是直接跳到你的书 :)?
    猜你喜欢
    • 1970-01-01
    • 2011-02-08
    • 2020-08-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-16
    相关资源
    最近更新 更多