Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript ignoring `typeRoots` when `noImplicitAny` is set

Tags:

typescript

I normally setup my tsconfig.json with strict set to true. This imply that noImplicitAny is also set to true. However, when strict is set, typescript seems to ignore my typeRoots entry for locally created *.d.ts file. Here is a sample tsconfig.json that I use:

{
    "compilerOptions": {
        "declaration": true,
        "emitDecoratorMetadata": true,
        "experimentalDecorators": true,
        "lib": [ "es2017" ],
        "module": "CommonJS",
        "noImplicitReturns": true,
        "outDir": "lib",
        "removeComments": true,
        "sourceMap": true,
        "strict": true,
        "target": "es2017",
        "typeRoots": [ "./typings", "./node_modules/@types" ],
        "types": [ "node" ],
    },
    "compileOnSave": true,
    "include": [ "./src/**/*" ]
}

I can add the following to tsconfig.json above and it will work:

{
    "compilerOptions": {
        ...
        "noImplicitAny": false,
        ...
    }
}

Here is a sample project I created to illustrate this problem:

https://github.com/marcoslin/tstyping-test

Any idea why this is happening?

like image 600
marcoseu Avatar asked Jan 21 '19 12:01

marcoseu


1 Answers

noImplicitAny: false does not really fix the problem it just ignores it. template will be implicitly typed as any as no types are found. You get no errors but no type safety either.

The real problem is that you specify "types": [ "node" ], this means that only the types for the node module are taken from typeRoots. See docs.

The simplest solution is to remove the types element from tsconfig.json. This tsconfig does not give any errors:

{
    "compilerOptions": {
        "declaration": true,
        "emitDecoratorMetadata": true,
        "experimentalDecorators": true,
        "lib": [ "es2017" ],
        "module": "CommonJS",
        "noImplicitReturns": true,
        "outDir": "lib",
        "removeComments": true,
        "sourceMap": true,
        "strict": true,
        "target": "es2017",
        "typeRoots": [ "./typings", "./node_modules/@types" ]
    },
    "compileOnSave": true,
    "include": [ "./src/**/*" ]
}
like image 56
Titian Cernicova-Dragomir Avatar answered Nov 10 '22 13:11

Titian Cernicova-Dragomir