typescript - 为什么 TypeScript 在尝试从联合类型中读取 never 时不报错?

标签 typescript

我认为 TypeScript尝试阅读属性时会提示 length什么可能是arraynever ,然后,我需要使用类型谓词缩小类型范围。不是这种情况。为什么 ?我怎样才能更改类型以便 TypeScript 强制我检查我不是在处理空对象?

// strictNullChecks = true
type Empty = Record<string, never>;

type NonEmpty = {
  documents: Array<number>;
};

function isEmpty(x: Empty | NonEmpty): x is Empty {
  return !("documents" in x);
}

const count = (x: Empty | NonEmpty) => {
  // TypeScript does not complain about reading `length` property of `never`
  // if (isEmpty(x)) {
  //   return 0;
  // }
  return x.documents.length;
};

最佳答案

下面是一个逐步类型的销毁示例:

type Empty = Record<string, never>;

type NonEmpty = {
  documents: Array<number>;
};

function isEmpty(x: Empty | NonEmpty): x is Empty {
  return !("documents" in x);
}

const count = (x: Empty | NonEmpty) => {

  type D0 = typeof x.documents
  type D1 =  (Empty | NonEmpty)[`documents`]
  type D2 = Empty[`documents`] | NonEmpty[`documents`]
  type D3 =  never | NonEmpty[`documents`]
  type D4 =  NonEmpty[`documents`]
  type D5 =  Array<number>

  return x.documents.length; // x.documents is number[], that's why no error here
};

以下是可能符合您需要的预期行为示例:

type EmptyExpected = Record<string, undefined>;

const countExpected = (x: EmptyExpected | NonEmpty) => {

  type D0 = typeof x.documents
  type D1 =  (EmptyExpected | NonEmpty)[`documents`]
  type D2 = EmptyExpected[`documents`] | NonEmpty[`documents`]
  type D3 =  undefined | NonEmpty[`documents`]
  type D4 =  undefined | number[]

  return x.documents.length; // x.documents is number[] | undefined, that's why it is an error here
};

TypeScript Playground

关于typescript - 为什么 TypeScript 在尝试从联合类型中读取 never 时不报错?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72109470/

相关文章:

javascript - 单击时 Angular 2 更改模板输入值

typescript - 使用 typescript 在 formik 错误中键入不匹配错误

使用类的静态成员进行 typescript 打字

typescript - 跟踪类实例中的状态

windows - 为什么在 Mac 上编译 TypeScript 比在 PC 上快得多?

具有原始值的 Angular onpush 变化检测策略

typescript - 如何在动态 Nestjs 模块中导入 registerAsync?

javascript - 遍历 Typescript 中的对象数组

javascript - SendGrid 客户端 TypeScript 错误 : HttpMethod

typescript :object.hasOwnProperty() 在继承属性上显示为真。为什么?