gpt4 book ai didi

typescript - TypeScript 中的奇怪对象可能是 "null"错误

转载 作者:行者123 更新时间:2023-12-04 14:47:41 24 4
gpt4 key购买 nike

我有这个简单的函数来检查未知值是否看起来像 Date 对象:

function looksLikeDate(obj: unknown): obj is { year: unknown; month: unknown; day: unknown } {
return (
obj !== null && typeof obj === "object" && "year" in obj && "month" in obj && "day" in obj
);
}

但是对于 obj 中的“year” 部分代码,我得到以下错误:

Object is possibly 'null'. (2531)

当我切换 obj !== nulltypeof obj === "object" 时,错误消失了:TS Playground Link

这不奇怪吗?谁能给我解释一下?

最佳答案

typeof null === 'object'

如果在 null 检查之后执行 typeof 检查,obj 可以 为空,即使您之前检查过 null,但 TS 编译器有点幼稚。

从这个意义上说,那些类型保护有点脆弱,如在您的示例中,typeof obj === 'object' 将类型从 “not null” 更改为对象 |空

关于typescript - TypeScript 中的奇怪对象可能是 "null"错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69720379/

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