Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

d.ts declare module not work when import third party libs

There are some Vscode tips "module not found" when declare module in d.ts dependency an third party module by import, is there any solution for it?

tsconfig.json

{
    "compilerOptions": {
        "outDir": "./dist/",
        "target": "es5",
        "lib": ["esnext", "dom.iterable","dom", "scripthost", "es2015.symbol"],
        "sourceMap": true,
        "noImplicitAny": true,
        "jsx": "react",
        "allowSyntheticDefaultImports": true,
        "experimentalDecorators": true,
        "emitDecoratorMetadata": true,
        "allowJs": true,
        "module": "commonjs",
        "isolatedModules": false,
        "esModuleInterop": true
    },
    "include": ["src/**/*","typings/*"],
    "exclude": ["node_modules"]
}

typings/index.d.ts

import * as moment from 'moment';

declare module 'someModule' {
    export function test(x: string): moment.CalendarKey;
}

enter image description here

but without import works fine

declare module 'someModule' {
    export function test(x: string): string;
}

enter image description here

what's problem?

like image 239
user1683012 Avatar asked Dec 13 '25 06:12

user1683012


1 Answers

You need to put moment import under the declare module:

declare module 'someModule' {
    import * as moment from 'moment';
    export function test(x: string): moment.CalendarKey;
}

This is needed because Typescript has different behavior if a file has top-level imports or exports (docs):

In TypeScript, just as in ECMAScript 2015, any file containing a top-level import or export is considered a module. Conversely, a file without any top-level import or export declarations is treated as a script whose contents are available in the global scope (and therefore to modules as well).

When you add an import at the top level, it turns your file into a module and declarations become scoped to this file only. When you move the import inside declaration, Typescript treats the file as script and declarations become available to other files in the project.

Also, see this question with a similar issue:

How to include ambient module declarations inside another ambient module?

like image 121
just-boris Avatar answered Dec 16 '25 02:12

just-boris



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!