V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
wdssmq
V2EX  ›  问与答

ts 引入作为配置项的 config.js 文件时如何解决类型问题?

  •  
  •   wdssmq · 2023-03-15 13:55:34 +08:00 · 676 次点击
    这是一个创建于 379 天前的主题,其中的信息可能已经有所发展或是发生改变。
    import config from '../config.js'
    
    src/main.ts:3:20 - error TS7016: Could not find a declaration file for module '../config.js'. 'path/config.js' implicitly has an 'any' type.
    
    第 1 条附言  ·  2023-03-15 15:42:44 +08:00
    ```js
    // config.d.ts
    import type { configInterface } from './src/types'
    declare const _default: configInterface
    export default _default

    // config.js
    exports.default = {
    // ...
    }
    ```

    ↑ 这样组合好像是可以用的,也算符合我的需要,但是写成 esm 导出就不行了;

    ```js
    // config.js
    const _default = {
    // ...
    }
    export { _default as default }
    ```

    报错:

    export { _default as default }
    ^^^^^^

    SyntaxError: Unexpected token 'export'

    虽然就结果上是解决了。。
    6 条回复    2023-03-15 17:05:54 +08:00
    sechi
        1
    sechi  
       2023-03-15 14:00:05 +08:00
    把 config.js 改成 config.ts 呗
    hua123s
        2
    hua123s  
       2023-03-15 14:04:07 +08:00
    写一个 config.d.ts 呗,不然就 ts-ignore
    wdssmq
        3
    wdssmq  
    OP
       2023-03-15 15:57:22 +08:00
    AI 给了条命令,姑且备忘下 - -

    tsc --allowJs --declaration --outDir ./typings config.js
    hua123s
        4
    hua123s  
       2023-03-15 16:24:56 +08:00
    @wdssmq 我不如 AI 😭😭😭
    wdssmq
        5
    wdssmq  
    OP
       2023-03-15 16:55:33 +08:00
    @hua123s 其实,我也没说 AI 的命令有用 - -

    现在变成了 config.default 才能拿到需要的对象,然后并没有定义到正确的类型。Orz
    wdssmq
        6
    wdssmq  
    OP
       2023-03-15 17:05:54 +08:00
    tsconfig 配置了 "allowJs": true, 好像可以了
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1223 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 20ms · UTC 18:07 · PVG 02:07 · LAX 11:07 · JFK 14:07
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.