繁体   English   中英

编译时未定义 TypeScript 枚举

[英]Undefined TypeScript enum at compile time

我在types.ts中定义了一个枚举:

export enum Handedness {
  Left,
  Right,
  Both,
}

export type State = {
  count: number
  handedness: Handedness
}

我在 state.ts 中初始化了一个state.ts

import { State, Handedness } from './types'

export const initial: State = {
  count: 0,
  handedness: Handedness.Both
}

当我为此项目运行测试(通过jest )时, state.ts生成错误TypeError: Cannot read property 'Both' of undefined ,告诉我Handedness在引用时未定义。 但是我在使用它之前从它的模块中导出它并导入它......所以它应该被定义。

我发现其他类似的问题询问未定义的枚举,但他们似乎都在询问运行时。 据我所知,这是一个编译时问题。

我不明白我会在这里做错什么。 我在其他地方导入其他类型没有问题。 但是这个枚举根本不想工作。 这是怎么回事,我该如何解决?

好吧,这不是让它工作的方法,但是这个 GitHub PR解释说ts-jest不支持像这样工作的枚举。 我已将所有用途更改为(例如) ("both" as Handedness)并且它有效。 所以,这不是解释,而是一种解决方法。

您也可以尝试使用const enums

所以改变:

export enum Whatever { ... }

export const enum Whatever { ... }

显然,从ts-jest版本 23.10 开始,您就可以这样做。 好多了!

我在用 Jest 运行我的代码时遇到了类似的错误。 该问题是由 React 组件从模块中导入枚举类型引起的,该模块也被 jest.mock 模拟。 我通过将 jest.spyOn 用于我需要的方法而不是整个模块来解决了这个问题。

来自: jest.mock("example/path", () => ({ useExampleMethod: () => {...

to: import * as exampleModule from "example/path"; jest.spyOn(exampleModule, 'useExampleMethod').mockReturnValue({... import * as exampleModule from "example/path"; jest.spyOn(exampleModule, 'useExampleMethod').mockReturnValue({...

此处存在类似问题,但原因和解决方案略有不同。 在这里发帖希望对其他人有所帮助。

  1. 我在文件/auth/types.ts中定义我的枚举:
....
export enum SampleEnum {
    FIRST = 1,
    SECOND = 2
}
  1. 然后我从/auth/index.ts导出我的类型:
export * from './types;
  1. 最后,我从应用程序其他地方的父目录导入它:
import { SampleEnum } from './auth'
...

const someOtherObject = {
  place: SampleEnum.FIRST
}

运行 Jest,我得到了TypeError: Cannot read property 'FIRST' of undefined错误,即使代码编译得很好。

为了解决这个问题,我将导入语句切换为

import { SampleEnum } from './auth/types'

暂无
暂无

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

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