【问题标题】:How to add typing file for third library?如何为第三个库添加打字文件?
【发布时间】:2019-01-01 20:19:26
【问题描述】:

我正在使用没有types 声明文件的第三个库。所以我需要在我的项目中添加库的类型。

但我试了很多次,结果总是错误。

这是我的tsconfig.json:

{
  "compilerOptions": {
    "baseUrl": ".",
    "esModuleInterop": true,
    "module": "commonjs",
    "moduleResolution": "node",
    "removeComments": true,
    "sourceMap": true,
    "target": "esnext",
    "types": ["node"],
    "strict": true,
    "paths": {
      "@/*": ["src/*"]
    }
  },
  "include": ["src/**/*"],
  "exclude": ["node_modules", "**/node_modules/*", "**/*.spec.ts"]
}

我在我的根项目中创建了一个global.d.ts 文件并声明了模块:

declare module 'matrix-js-sdk' {
  interface Promise {
    done(callback: () => void): void
  }

  interface Client {
    joinRoom(roomId: string): Promise
  }

  export function createClient(options: {
    baseUrl: string
    accessToken: string
    userId: string
  }): Client
}

导入第三个库:

import sdk from 'matrix-js-sdk'
// error: Cann't find the declaration file for the module 'matrix-js-sdk'

另外,我还尝试创建root/src/@types/matrix-js-sdk/index.d.ts文件并写声明:

interface Promise {
  done(callback: () => void): void
}

interface Client {
  joinRoom(roomId: string): Promise
}

export function createClient(options: {
  baseUrl: string
  accessToken: string
  userId: string
}): Client

但它永远不会起作用。


==================已更新====================

现在我可以在src/global.d.ts(不是根项目)中编写声明,并将其引用到编译中:

/// <reference path="../global.d.ts" />

import sdk from 'matrix-js-sdk'

但不推荐reference语法,我尝试在tsconfig.json的files字段中包含src/global.d.ts:

"files": ["src/global.d.ts"],
"include": ["src/**/*"],
"exclude": ["node_modules", "**/node_modules/*", "**/*.spec.ts"]

它再次抛出同样的错误:

Could not find a declaration file for module 'matrix-js-sdk'

另一个,src/@types/matrix-js-sdk/index.d.ts 还是不行(我更喜欢用这种方式)。

【问题讨论】:

    标签: typescript type-declaration


    【解决方案1】:

    你能试试吗

    declare module 'matrix-js-sdk' {
      interface Promise {
        done(callback: () => void): void
      }
    
      interface Client {
        joinRoom(roomId: string): Promise
      }
    
      export function createClient(options: {
        baseUrl: string
        accessToken: string
        userId: string
      }): Client
    }
    

    在src/@types/matrix-js-sdk/index.d.ts

    您的声明文件中也没有默认导出,因此import sdk from... 会给出一些与此相关的错误。

    【讨论】:

    • 你是对的!谢谢!并且需要在tsconfig.json中配置typeRoots:"typeRoots": ["./src/@types", "./node_modules/@types"]
    • 你知道上面global.d.ts的问题吗?
    • 我已将 src/@types/matrix-js-sdk/index.d.ts 移动到 src/global.d.ts 并且 vscode 仍然能够导航到正确的 d.ts 文件,而在 files 中没有 files 属性tsconfig.json
    猜你喜欢
    • 2022-07-22
    • 1970-01-01
    • 2019-10-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-03
    • 1970-01-01
    相关资源
    最近更新 更多