junlin
junlin

Reputation: 2035

How to add typing file for third library?

I'm using a third library that withou types declaration file. So I need to add the typings for the library in my project.

But I had tried it many times with always wrong result.

Here is my 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"]
}

I created a global.d.ts file in my root project and declared the module:

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 third library:

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

In addition, I also tried to create root/src/@types/matrix-js-sdk/index.d.ts file and write the declaration:

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

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

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

But it never works.


================== Updated ====================

Now I can write declaration in src/global.d.ts (not root project), and refer it to be included in compilation:

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

import sdk from 'matrix-js-sdk'

But the reference syntax is not recommended, and I tried to include the src/global.d.ts in files field in tsconfig.json:

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

It throw the same error again:

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

Another, the src/@types/matrix-js-sdk/index.d.ts still not works(I prefer to use this way).

Upvotes: 2

Views: 850

Answers (1)

tonakai
tonakai

Reputation: 835

can you try to put

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
}

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

also there is no default export in your declaration file so import sdk from... will give some errors related to that.

Upvotes: 1

Related Questions