我有一个简单的情况,即使我显式检查未定义,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
答案 0 :(得分:1)
类型防护仅适用于类型,不适用于属性,这意味着:
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;
};
答案 1 :(得分:1)
为了适当地缩小类型,您可以采用以下形式创建自定义类型防护:
const isNarrow = (a: WideType): a is NarrowType => !!a.one;
在您的示例中使用:
interface WideType {
one: { two: number } | undefined;
}
interface NarrowType {
one: { two: number };
}
const isNarrow = (a: WideType): a is NarrowType => !!a.one;
const example = (value: WideType): NarrowType | null => {
if (isNarrow(value)) {
return value; // value is NarrowType
}
return null;
};