2

I'm setting up TypeScript in an existing JS project, and I'm trying to figure out how to add typings to an untyped npm module, since I know it'll come up.

This line

import X from 'foo';

errors out with Cannot find module 'foo'

In typings/modules I have a foo folder with an index.d.ts file therein with

declare module foo {
    export default class XXX{

    }
}

In the parent typings/index.d.ts I've added

/// <reference path="modules/foo/index.d.ts" />

But still nothing.

My tsconfig.json file looks like this

{
    "compilerOptions": {
        "target": "esnext",
        "baseUrl": "./src",
        "jsx": "react",
        "allowSyntheticDefaultImports": true,
        "allowJs": true,
        "moduleResolution": "node",
        "module": "es2015",
        "experimentalDecorators": true,
        "lib": ["es2015", "dom"],
        "typeRoots" : ["./typings/modules", "./node_modules/@types"]
    },
    "include": [
        "./src/**/*.ts",
        "./src/**/*.tsx"
    ]
}

1 Answer 1

2

You have to declare your module with quotes:

declare module "foo" {
    export default class XXX{

    }
}

Seems crazy? Modules declared without quotes are actually similar to namespaces. So you are not actually declaring a module in your code.

From the documentation:

“Internal modules” are now “namespaces”. “External modules” are now simply “modules”, as to align with ECMAScript 2015’s terminology, (namely that module X { is equivalent to the now-preferred namespace X {).

Also see: What's the difference between declaring a module in TypeScript with quotes vs without?

Sign up to request clarification or add additional context in comments.

1 Comment

plus one thanks. Will test as soon as I'm not afk and accept.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.