TypeScript 中 cannot read property of undefined 错误

枚举错误 – 无法读取未定义属性的发生有两个主要原因:

  1. 使用在编译期间被删除的 const 枚举。
  2. 具有循环导入(在相同文件之间导入成员)。

要解决枚举错误 – “cannot read property of undefined”,请确保在声明枚举时删除 const 关键字并从代码库中删除任何循环导入。

export const enum Sizes {
  Small = 'S',
  Medium = 'M',
  Large = 'L',
}

上面的示例声明了一个 const 枚举。

使用 const 枚举可能会非常混乱,而且通常不鼓励使用。

TypeScript 中的常规枚举是真实对象,存在于运行时。 但是,const enum 成员在使用站点内联并且在运行时不可用,这可能会导致错误。

这是一个循环导入的例子。

import { EmailStatus } from './another-file';

// ✅ For String Enums
export enum Sizes {
  Small = 'S',
  Medium = 'M',
  Large = 'L',
}

// 👇️ Use EmailStatus here

这是导入 Sizes 枚举的另一个文件。

another-file.ts

import { Sizes } from './index';

export enum EmailStatus {
  Read = 'READ',
  Unread = 'UNREAD',
  Draft = 'DRAFT',
}

// 👇️ Use Sizes here

我们在两个文件之间导入和导出成员,因此它们相互依赖。

这对 TypeScript 编译器来说非常混乱,应该避免。

相反,我们可以将枚举移动到单个文件,导出它们,然后在另一个文件中使用它们,而无需在两个文件之间进行循环导入。

import { EmailStatus, Sizes } from './another-file';

// 👇️ Use EmailStatus and Sizes here

这是另一个文件的内容。

another-file.ts

export enum EmailStatus {
  Read = 'READ',
  Unread = 'UNREAD',
  Draft = 'DRAFT',
}

export enum Sizes {
  Small = 'S',
  Medium = 'M',
  Large = 'L',
}

现在我们在两个文件之间没有任何循环导入,并且 TypeScript 在运行我们的代码时不会混淆。