【问题标题】:TypeScript type guard OddityTypeScript 类型保护 Oddity
【发布时间】:2016-04-29 21:50:22
【问题描述】:

我在循环内的三元运算符中使用 TypeScript 类型保护,并看到我不理解的行为。

我的界面

interface INamed {
    name: string;
}

interface IOtherNamed extends INamed {
    otherName: string;
}

我的打字员

function isOther(obj: any): obj is IOtherNamed {
    ... // some check that returns boolean
}

一般用法示例

var list: Array<{named: INamed}> = [];

for(let item of list) {
    var other: IOtherNamed = ...
}

在我的 for .. of 循环中,我使用我的类型保护将我当前的项目或 null 分配给 IOtherNamed 的变量。

这不起作用

// Compiler Error: INamed is not assignable to IOtherNamed
for(let item of list) {
    var other: IOtherNamed = isOther(item.named) ? item.named : null;
}

确实如此

for(let item of list) {
    var named: INamed = item.named;
    var other2: IOtherNamed = isOther(named) ? named : null;
}

我的问题

  1. 这是设计使其中一个有效而另一个无效吗?
  2. 如果设计使然,这里的细微差别决定了它何时起作用?特别是为什么将我的对象分配给一个新变量(没有任何类型更改)可以消除编译器错误?

【问题讨论】:

    标签: typescript typescript1.6


    【解决方案1】:

    是的,这是为 TypeScript

    请注意,类型保护只影响变量和参数的类型,对属性等对象的成员没有影响。

    — 语言规范中的 4.20(PDF,第 83 页)

    所以它在第二种情况下起作用的原因是因为您已将属性分配给一个变量,然后键入保护该变量。

    更新:正如 Alex 指出的,TypeScript 2.0 将支持属性的类型保护。

    【讨论】:

      猜你喜欢
      • 2020-02-01
      • 2021-01-22
      • 2019-01-04
      • 1970-01-01
      • 2020-11-11
      • 2021-12-10
      • 2018-12-03
      • 1970-01-01
      • 2023-01-23
      相关资源
      最近更新 更多