Home > Back-end >  How to import types from a third party library?
How to import types from a third party library?

Time:12-27

I have a third party library which has types declared in node_modules/thisLibrary/dist/interfaces.d.ts. TS compiler resolves the types used in a function imported from this library, because tooltip displays them and also errors appear when I make incorrect assignments, but when I want to declare a variable using the library's type (which I obviously need to do), I get the error Cannot find name 'TypeName':

let myVar: TypeName; // `Cannot find name 'TypeName'`

I have the following settings in my tsconfig.json:

"moduleResolution": "node",
   "include": [
        "src/**/*.ts",
        "src/**/*.tsx",
        "src/**/*.vue",
        "tests/**/*.ts",
        "tests/**/*.tsx",
        "node_modules/thisLibrary/dist/interfaces.d.ts",
        "../node_modules/thisLibrary/dist/interfaces.d.ts", // attempting various paths
    ],
 "typeRoots": [
        "node_modules/@types",
        "node_modules/thisLibrary/dist",
    ],

I added the include and typeRoots following some answers, but nothing helps. Compiler does not see it and the library does not export the types (as in the library module), so I'm not able to import them:

import {type TypeName} from 'thisLibrary'; // results in "Module 'thisLibrary' has no exported member 'TypeName'".

How can I solve this problem?

CodePudding user response:

Try to import directly from the file where the exported interface is located.

import { TypeName } from 'thisLibrary/dist/interfaces'

CodePudding user response:

You said that the types are exported from the lib, so just import the type from the lib, like this:

import type {TypeName} from 'thisLibrary';
// or in TS version >=4.5
import {type TypeName} from 'thisLibrary';

let myVar: TypeName; // ok

TS Playground example

  • Related