gpt4 book ai didi

TypeScript 类型保护 Oddity

转载 作者:搜寻专家 更新时间:2023-10-30 20:40:34 26 4
gpt4 key购买 nike

我在一个循环中的三元运算符中使用 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 < 2.0 设计的:

Note that type guards affect types of variables and parameters only and have no effect on members of objects such as properties.

— 4.20 from the language specification (PDF, page 83)

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

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

关于TypeScript 类型保护 Oddity,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33478986/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com