How to import other types in to a typescript .d.ts module

1.5k Views Asked by At

I have a custom .d.ts file for an external module that looks like

declare module 'vertices-bounding-box' {
  export default function boundingBox(positions: [number,number,number][]): [number, number]
}

Instead of [number,number,number] I would like to use a type from another module like:

import { vec3 } from 'gl-matrix';

declare module 'vertices-bounding-box' {
  export default function boundingBox(positions: vec3[]): [number, number]
}

TSC complains when I add the import statement for vec3 saying:

Invalid module name in augmentation. Module 'vertices-bounding-box' resolves to an untyped
module at '/Users/kevzettler/code/hypeworks/node_modules/vertices-bounding-box/index.js', which cannot be augmented. [2665]
1

There are 1 best solutions below

0
On BEST ANSWER

You just showed the most prevalent use case for import types in TypeScript:

Modules can import types declared in other modules. But non-module global scripts cannot access types declared in modules. Enter import types.

In other words, this language feature allows to import types of an external module 'gl-matrix' from within the global scope of your project .d.ts file like this:

// ext-module.d.ts, important: don't use ES import statement here
declare module 'vertices-bounding-box' {
  export default function boundingBox(
    positions: Array<import("gl-matrix").vec3>): [number, number]
}

Note: A file without ES import/export is a global script and not a module.

'vertices-bounding-box' does not come with its own types, so these need to be declared in a global script file as shown above. For cases, where you wanted to extend already existing types like from DefinitelyTyped / @types, you would keep the top-level ES import

import { vec3 } from 'gl-matrix';
// ...

in this file, as module augmentation needs a module.