Jodiug Jodiug - 1 month ago 44
TypeScript Question

TypeScript 2: custom typings for untyped npm module

After trying suggestions posted in other places, I find myself unable to get a typescript project running that uses an untyped NPM module. Below is a minimal example and the steps that I tried.

For this minimal example, we will pretend that

lodash
does not have existing type definitions. As such, we will ignore the package
@types/lodash
and try to manually add its typings file
lodash.d.ts
to our project.

Folder structure


  • node_modules


    • lodash


  • src


    • foo.ts


  • typings


    • custom


      • lodash.d.ts


    • global

    • index.d.ts


  • package.json

  • tsconfig.json

  • typings.json



Next, the files.

File
foo.ts


///<reference path="../typings/custom/lodash.d.ts" />
import * as lodash from 'lodash';

console.log('Weeee');


File
lodash.d.ts
is copied directly from the original
@types/lodash
package.

File
index.d.ts


/// <reference path="custom/lodash.d.ts" />
/// <reference path="globals/lodash/index.d.ts" />


File
package.json


{
"name": "ts",
"version": "1.0.0",
"description": "",
"main": "index.js",
"typings": "./typings/index.d.ts",
"dependencies": {
"lodash": "^4.16.4"
},
"author": "",
"license": "ISC"
}


File
tsconfig.json


{
"compilerOptions": {
"target": "ES6",
"jsx": "react",
"module": "commonjs",
"sourceMap": true,
"noImplicitAny": true,
"experimentalDecorators": true,
"typeRoots" : ["./typings"],
"types": ["lodash"]
},
"include": [
"typings/**/*",
"src/**/*"
],
"exclude": [
"node_modules",
"**/*.spec.ts"
]
}


File
typings.json


{
"name": "TestName",
"version": false,
"globalDependencies": {
"lodash": "file:typings/custom/lodash.d.ts"
}
}


As you can see, I have tried many different ways of importing typings:


  1. By directly importing it in
    foo.ts

  2. By a
    typings
    property in
    package.json

  3. By using
    typeRoots
    in
    tsconfig.json
    with a file
    typings/index.d.ts

  4. By using an explicit
    types
    in
    tsconfig.json

  5. By including the
    types
    directory in
    tsconfig.json

  6. By making a custom
    typings.json
    file and running
    typings install



Yet, when I run Typescript:

E:\temp\ts>tsc
error TS2688: Cannot find type definition file for 'lodash'.


What am I doing wrong?

Answer

I still don't understand this, but I found a solution. Use the following tsconfig.json:

{
  "compilerOptions": {
    "target": "ES6",
    "jsx": "react",
    "module": "commonjs",
    "sourceMap": true,
    "noImplicitAny": true,
    "experimentalDecorators": true,
    "baseUrl": ".",
    "paths": {
      "*": [
        "./typings/*"
      ]
    }
  },
  "include": [
    "src/**/*"
  ],
  "exclude": [
    "node_modules",
    "**/*.spec.ts"
  ]
}

Remove typings.json and everything under folder typings except lodash.d.ts. Also remove all the ///... references