Typescript 字体字体保护奇怪

Typescript 字体字体保护奇怪,typescript,typescript1.6,Typescript,Typescript1.6,我在循环中的三元运算符中使用TypeScript类型保护,看到了一个我不理解的行为 我的界面 interface INamed { name: string; } interface IOtherNamed extends INamed { otherName: string; } for(let item of list) { var named: INamed = item.named; var other2: IOtherNamed = isOther(

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

我的界面

interface INamed {
    name: string;
}

interface IOtherNamed extends INamed {
    otherName: string;
}
for(let item of list) {
    var named: INamed = item.named;
    var other2: IOtherNamed = isOther(named) ? named : null;
}
My type guard

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 = ...
}
确实如此

interface INamed {
    name: string;
}

interface IOtherNamed extends INamed {
    otherName: string;
}
for(let item of list) {
    var named: INamed = item.named;
    var other2: IOtherNamed = isOther(named) ? named : null;
}
我的问题

interface INamed {
    name: string;
}

interface IOtherNamed extends INamed {
    otherName: string;
}
for(let item of list) {
    var named: INamed = item.named;
    var other2: IOtherNamed = isOther(named) ? named : null;
}
  • 这是一种设计,其中一种有效,而另一种无效吗
  • 如果是设计的,这里的细微差别决定了它何时起作用?特别是,为什么将我的对象分配给新变量(没有任何类型更改)可以消除编译器错误

  • 是的,这是为TypeScript<2.0设计的:

    请注意,类型保护只影响变量和参数的类型,而不影响对象的成员,例如属性

    -语言规范中的4.20(第83页)

    因此,它在第二种情况下工作的原因是,您已将属性分配给变量,然后键入该变量

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