简体   繁体   English

Typescript strictNullChecks 不窄类型

[英]Typescript strictNullChecks does not narrow type

I have a simple case when strictNullChecks does not narrow type even though I explicitly check for undefined.我有一个简单的情况,即使我明确检查未定义, 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;
};

The error message is:错误信息是:

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)

How do I help TS compiler to figure that out?我如何帮助 TS 编译器解决这个问题? TS version 3.7.2 TS 版本 3.7.2

Type guard only works on a type, not on a property, which means:类型保护仅适用于类型,而不适用于属性,这意味着:

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;
};

In order to properly narrow the type you can create custom type guard in a form:为了正确缩小类型,您可以在表单中创建自定义类型保护:

const isNarrow = (a: WideType): a is NarrowType => !!a.one;

Using in your example:在您的示例中使用:

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;
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM