gpt4 book ai didi

typescript - 引用从 npm 类型导入的枚举时出错

转载 作者:行者123 更新时间:2023-12-04 15:58:31 34 4
gpt4 key购买 nike

我最近向私有(private) npm 模块添加了类型。

模块的导出类型之一是以下枚举:

export enum ServerResponseCode {
LoginFailed: 'loginFailed',
LoginExpired: 'loginExpired'
}

然后它被另一个 typescript 项目导入并使用如下:
import { ServerResponseCode } from 'private-module'

if(response.code === ServerResponseCode.LoginExpired)

此代码不会引发任何编译错误,但在运行时出现错误:“无法读取未定义的 LoginExpired 属性”

为什么会发生这种情况,我该如何解决?

最佳答案

解决方案是简单地导出一个 const enum在私有(private)模块的类型声明文件中:

export const enum ServerResponseCode {
LoginFailed: 'loginFailed',
LoginExpired: 'loginExpired'
}

来自此的简短说明 stackoverflow thread :

枚举定义为 const以便对其元素的任何引用都内联(由 ts 编译器),这样可以避免运行时查找 ServerResponseCode对象实际上是 undefined (因为 .d.ts 文件不会产生任何 JS)。

关于typescript - 引用从 npm 类型导入的枚举时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51035040/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com