找不到打字稿类型声明

Posted

技术标签:

【中文标题】找不到打字稿类型声明【英文标题】:Typescript Types declaration not found 【发布时间】:2022-01-06 11:36:54 【问题描述】:

当我在类型声明文件中遇到问题时,我正在使用 TypeScript 编写一个小型 Discord 机器人。

index.d.ts:

declare module 'configuration' 
    /**
     * Configuration of your bot.
     */
    export type IConfiguration = 
        /**
         * Token of your bot.
         */
        token: string
        /**
         * Prefix of your bot.
         */
        prefix: string
        /**
         * Time to cool down the bot commands.
         */
        coolDown: number
    
    /**
     * Context at which we are logging.
     */
    export type IContext = '[Bot]' | '[Client]' | '[Server]'

    /**
     * Type for the commands
     */
    export type ICommand = (message: Message, arguments: string[]) => void | any 

显然 index.ts 无法加载声明文件?

执行import IConfiguration, ICommand from 'configuration'; 只会返回错误: Cannot find module 'configuration' or its corresponding type declarations.ts(2307)

我一直在网上寻找,提到的一些解决方案在 package.json 和 tsconfig.json 中列出了您的类型,但似乎都没有帮助。

TSConfig.json:


    "compilerOptions": 
      "allowJs": true,
      "checkJs": true,
      "noEmit": true,
      "target": "es2015",
      "module": "commonjs",
      "resolveJsonModule": true,
      // TBD it is desired to enabled strict type checking at some point:
      "strict": false,
      "typeRoots": ["./types", "./node_modules/@types"]
    

我不知道为什么这不起作用。非常感谢。

【问题讨论】:

【参考方案1】:

找出发生了什么。

显然 ES Module import 和 typescript declare module 不是很好的朋友...不知道为什么它不想工作,但是当我将所有类型导出到根级别时:

/**
 * Type for the commands
 */
export type ICommand = (message: Message, arguments: string[]) => void | any 

/**
 * Context at which we are logging.
 */
export type IContext = '[Bot]' | '[Client]' | '[Server]'

/**
* Configuration of your bot.
*/
export type  IConfiguration = 

    /**
    * Token of your bot.
    */
    token: string

    /**
    * Prefix of your bot.
    */
    prefix: string

    /**
    * Time to cool down the bot commands.
    */
    coolDown: number

它工作得很好。如果有人知道为什么会这样,请告诉我!

【讨论】:

以上是关于找不到打字稿类型声明的主要内容,如果未能解决你的问题,请参考以下文章

打字稿给出,“找不到模块'xmlhttprequest'的声明文件。”

库的打字稿声明文件找不到模块

打字稿编译器找不到带有纱线的节点-找不到“节点”的类型定义文件

在打字稿中找不到名称“省略”

错误:“HTMLDivElement”类型上不存在属性“值”?打字稿找不到我的div?

打字稿找不到 .d.ts 文件