Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

app.d.ts 写的有问题,编译后的 index.d.ts 会报错 #11

Closed
WhiteMinds opened this issue Oct 20, 2022 · 5 comments
Closed

app.d.ts 写的有问题,编译后的 index.d.ts 会报错 #11

WhiteMinds opened this issue Oct 20, 2022 · 5 comments
Labels
bug Something isn't working enhancement New feature or request

Comments

@WhiteMinds
Copy link

WhiteMinds commented Oct 20, 2022

因为 app.d.ts 里有个 export enum GuardLevel,现在会编译到 index.d.ts 里变成 enum GuardLevel,然后引入这个包后就会报错:

// file: index.ts
import { startListen, MsgHandler } from 'blive-message-listener'
// ... codes ...
$ tsc
node_modules/blive-message-listener/dist/index.d.ts:41:1 - error TS1046: Top-level declarations in .d.ts files must start with either a 'declare' or 'export' modifier.

编译的时候 d.ts 和 ts 的处理是不同的,其实按你这个项目的用途来看,app 不应该是 d.ts,而是一个正常的 ts 文件,因为按照官方的解释 microsoft/TypeScript#5112 (comment) ,d.ts 文件应该是构建系统的输入,不应该参与到输出,而你 app 文件里全是用于输出的,所以应该是 ts 文件,那样就可以编译成正常的 declare enum GuardLevel

@WhiteMinds
Copy link
Author

另外,定义了 enum 但只导出它的 type 这个行为其实也不太好,包的使用者还得自己再定义遍 enum

@ddiu8081
Copy link
Owner

ddiu8081 commented Oct 20, 2022

感谢指出!我看 #12 被 Close 了没有合并,需要重新打开么?

另外,定义了 enum 但只导出它的 type 这个行为其实也不太好,包的使用者还得自己再定义遍 enum

在我个人使用来看,是通过 import type { GuardLevel } from 'blive-message-listener' 就可以导入并使用的,似乎不用重新定义?

@WhiteMinds
Copy link
Author

WhiteMinds commented Oct 20, 2022

呃,#12 不用重新打开,那个是我试了下 github 的在线编辑功能,还挺好使的。

因为 GuardLevel 导出时用的是 export type,所以不会编译到 js 里,GuardLevel 这个变量实际上不存在于 dist/index.js 中。
类型上是没问题,但是当作数据来用的话会出问题,比如 identity.guard_level === GuardLevel.Zongdu

ddiu8081 added a commit that referenced this issue Oct 20, 2022
@ddiu8081 ddiu8081 added bug Something isn't working enhancement New feature or request labels Oct 20, 2022
@ddiu8081
Copy link
Owner

v0.3.1 已修正;
枚举在 JavaScript 环境使用的话似乎没想到什么方案(枚举改为导出 Object?)目前我的想法还是 TS 用枚举 JS 用 number 判断🤔

@WhiteMinds
Copy link
Author

v0.3.1 已修正; 枚举在 JavaScript 环境使用的话似乎没想到什么方案(枚举改为导出 Object?)目前我的想法还是 TS 用枚举 JS 用 number 判断🤔

就正常编译到 es5 成 object 就行,tsc 把 enum 编译成 object 后,类型上还是 enum。
目前这种情况 TS 开发环境下也用不了枚举,因为 import 出来的只有类型,必须手动重新定义一个同样的 enum。
或者可以转一遍数据变成字符串的版本:

export type GuardLevel = 'None' | 'ZongDu' | 'TiDu' | 'JianZhang'

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

2 participants