2015-11-02 69 views
6

我在循环内的三元运算符中使用TypeScript类型的警卫,并看到我不明白的行为。TypeScript类型的警卫Oddity

我的接口

interface INamed { 
    name: string; 
} 

interface IOtherNamed extends INamed { 
    otherName: string; 
} 

我型后卫

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

一般使用Sample

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

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

在我的循环内部,我正在使用我的类型守护程序将我当前的项目或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. 这是由设计,这些作品的一个Wh是ile另一个不?
  2. 如果按照设计,这里的细微差别决定了它的工作与否?特别是为什么分配我的对象到一个新的变量(没有任何类型的变化)摆脱编译器错误?

回答

4

对,这是通过设计用于打字稿< 2.0:

注意,类型警卫影响类型的变量和参数仅和对对象的成员,诸如性能没有影响。

- 4.20从语言规范(PDF,第83页)

所以它工作在第二种情形的原因是因为你已经分配的财产,以一个变量,然后键入守卫该变量。

更新:正如Alex指出的那样,TypeScript 2.0将支持属性上的类型警卫。

+0

非常感谢,我需要的信息。 – bingles

+0

并将在TS 2.0中修复:https://github.com/Microsoft/TypeScript/issues/3812 – Alex