typescript - 打字稿 strictNullChecks 不会缩小类型
问题描述
即使我明确检查未定义,我也有一个简单的情况,strictNullChecks
即不缩小类型。
interface WideType {
one: { two: number } | undefined;
}
interface NarrowType {
one: { two: number };
}
const example = (value: WideType): NarrowType | null => {
if (value.one) {
return value; // I have an error here
}
return null;
};
错误信息是:
Type 'WideType' is not assignable to type 'NarrowType'.
Types of property 'one' are incompatible.
Type '{ two: number; } | undefined' is not assignable to type '{ two: number; }'.
Type 'undefined' is not assignable to type '{ two: number; }'.ts(2322)
我如何帮助 TS 编译器解决这个问题?TS 版本 3.7.2
解决方案
类型保护仅适用于类型,而不适用于属性,这意味着:
interface WideType {
one: { two: number } | undefined;
}
interface NarrowType {
one: { two: number };
}
const example = (value: WideType): NarrowType | null => {
if (value.one) {
// return value; // You have an error here, as value.one is not undefined, but value is still a WideType
return {one: value.one}; // This works as value.one is not undefined
}
return null;
};
推荐阅读
- android - 在 Firestore 上获取文档有时会返回 client.user 不能为空
- android - 是否有一个类似于 expandtile 的小部件,它允许我将标题作为单独的按钮单击?
- asp.net-core - 图分页示例
- c++ - 在数组中搜索时间
- java - Java 中的 AWS DynamoDB 分区键锁定实施
- angularjs - 在 d3 桑基图中显示实时更新
- javascript - 箭头函数在取值时表现不同的逻辑是什么?
- elasticsearch - Elasticsearch,同样的查询带来不同的结果
- binary - 在 Fortran 中使用原始二进制数据编写一个 .vtu 文件(paraview)
- html - 来自数组的AngularJS表