[Typescript] Augmenting Modules with Declarations

In lodash, you can use 'mixin' to create a new function on lodash object.

import * as _ from 'lodash';

_.chunk([1, 2, 3, 4], 2); // [[1,2], [3,4]]

_.mixin({
  log(item: string) {
    console.log(':::', item);
  },
});

_.log('Hello!');

 

The problem is, typescript doesn't know about '_.log', since this is created by mixin.

 

The way to solve the problem is by create types:

// src/@typs/lodash/index.d.ts
import * as lodash from 'lodash';

declare module 'lodash' {
  interface LoDashStatic {
    log(item: string): void;
  }
}

 

We also need to tell typescript compile where to locate those types informtaion:

// tsconfig.json
{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "lib": ["dom", "es6"],
    "outDir": "dist",
    "typeRoots": ["src/@types", "node_modules/@types"]
  }
}

 

posted @ 2020-10-09 01:19  Zhentiw  阅读(85)  评论(0编辑  收藏  举报