gpt4 book ai didi

javascript - Typescript 属性 'property' 在类型 'void | 上不存在 |样本

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

根据 Typescript voidsupertype nullundefined 类型。因此,具有 void 类型的函数可以返回 nullundefined

唯一的问题是当我尝试使用 typeof val !== 'undefined'val !== undefined 进行编译时。第二个失败了,但第一个有效。

根据文档 typeof null 应该是 objecttypeof undefinedundefined ( see here )

那么,第一个方法编译成功而第二个方法失败的原因是什么?这对我来说没有任何意义。

interface IFace {
data: string;
}

function sample(): void | IFace { // void could be null or undefined
return null;
}

let value = sample();

if( value !== undefined )
console.log(value.data); // It fails because value could be null

if( typeof value !== 'undefined' )
console.log(value.data); // Why is it working? typeof value could be object (because null)

See DEMO

似乎 typeof value !== 'undefined' 被解释为一个对象(因为 typeof nulltypeof IFace 是对象)。但是 null 对象那里没有数据字段,所以它应该失败吗?

已更新根据TypeScript documentationstrictNullChecks 选项设置为 true 可以解决这个问题:

In strict null checking mode, the null and undefined values are not in the domain of every type and are only assignable to themselves and any (the one exception being that undefined is also assignable to void). So, whereas T and T | undefined are considered synonymous in regular type checking mode (because undefined is considered a subtype of any T), they are different types in strict type checking mode, and only T | undefined permits undefined values. The same is true for the relationship of T to T | null.

但我不知道为什么 typeofstrictNullChecks 设置为 false。根据this TypeScript issue因为 typeof 起作用的原因似乎是编译器没有为了类型检查的目的在表达式中特例 typeof

最佳答案

如文档中所述。

Union types can be a bit tricky here, but it just takes a bit of intuition to get used to. If a value has the type A | B, we only know for certain that it has members that both A and B have. In this example, Bird has a member named fly. We can’t be sure whether a variable typed as Bird | Fish has a fly method. If the variable is really a Fish at runtime, then calling pet.fly() will fail.

在您的示例中,void 没有属性“数据”。因此在以下情况下无法识别:

if( value !== undefined ) 
console.log(value.data);

您还可以按如下方式更新它以使其工作:

if( (<IFace>value).data !== undefined )
console.log((<IFace>value).data);

然后出现了称为类型守卫的东西。 typescript 将 typeof 识别为类型保护之一。

These typeof type guards are recognized in two different forms: typeof v === "typename" and typeof v !== "typename", where "typename" must be "number", "string", "boolean", or "symbol". While TypeScript won’t stop you from comparing to other strings, the language won’t recognize those expressions as type guards.

这里是 link了解更多信息。

关于javascript - Typescript 属性 'property' 在类型 'void | 上不存在 |样本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55360626/

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