首页 > 解决方案 > 为我的项目扩展 lodash 类型(@types/lodash),使用“first”方法的接口

问题描述

问题: 我发现@types/lodash 方法首先没有涵盖输入的案例类型是两个(多个)类型化数组的联合://在我的文件中,我有 import * as _ from 'lodash';

interface First {
  name: string;
}

interface Second {
  age: number;
}

function performSomeLogic(): First[] | Second[] {
  if (Math.random() > 0.5) return [{name: 'Alice'}, {name: 'Bob'}];
  return [{age: 42}, {age: 33}];
}

// we got some array First or Second of type. ok
const returnedData = performSomeLogic(); // we got some array First or Second of type. ok

// we expect value is First or Second of type. NOT ok.

// *******************
// TS ERROR
// TS2345: Argument of type 'First[] | Second[]' is not assignable to 
// parameter of type 'ArrayLike<First>'.
// *******************
const firstValueOfData = _.first(returnedData); 

// further steps could be ..
const proceedWithValueOfData = (value: First | Second) => Object.keys(value);
proceedWithValueOfData(firstValueOfData);

想法: 我想出了_.first()的正确接口。我尝试将其放入 typings.d.ts 添加参考它以供捆绑器使用:

// typings.d.ts
type DeriveArrTypes<T> = T extends (infer R)[] ? R : T;

// So DeriveArrTypes<First[] | Second[]> returns First|Second union

declare module 'lodash' {
  // LoDashStatic IS THE INTERFACE LODASH HAS HAD. FIRST IS DECLARED IN IT. I WANT TO ADD ITS EXTENDED DECLARATION
  interface LoDashStatic {
    first<T extends []>(value: T): DeriveArrTypes<T> | undefined;
  }
}

成功 - 否: 但这不起作用。Typescript 停止显示任何错误(包括其他不同的错误)。我使用 WebStorm 作为 IDE,它继续突出显示。

ENV: 它是一个前端项目,由 Typescript 用于转译和 Webpack 用于捆绑(由于其长期持续的活跃性:))。从webpack.config.js

       // the rule for ts
       {
            test: /\.ts$/,
            use: [{
                loader: 'ts-loader',
                options: {
                    // disable type checker - we will use it in fork plugin
                    transpileOnly: true
                }
            }],
        },

       // plugins section
       plugins: [
         // bla-bla plugins
         ...

        new ForkTsCheckerWebpackPlugin({
          tsconfig: __dirname + '/tsconfig.json'
        })
      ]

tsconfig.json

"compilerOptions": {
      // bla-bla options
      ... 

      "typeRoots": [
        "node_modules/@types"
      ],
 }

 // I ADDED THIS
 "include": [
    "app/typings/**/*"
  ],

当我创建app/ typings目录并将typings.d.ts放入其中时。

标签: typescriptlodashtypescript-typingsdefinitelytyped

解决方案


If you want to add interface to a npm module you can use declare module keyword

import lodash  from "lodash";
declare module "lodash " {
    interface First {
       name: string;
    }

    interface Second {
      age: number;
    }
}

推荐阅读