通过我的项目的“ first”方法接口扩展lodash类型@ types / lodash

问题描述

问题: 我发现@ types / lodash方法首先没有涵盖输入是两个(多个)类型数组的并集的情况: //在我的档案中 从'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()设计了正确的界面。我尝试将其放入types.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 放入其中时。

解决方法

如果要将接口添加到npm模块,则可以使用>>> from sympy import symbols >>> from sympy.plotting import plot >>> x = symbols('x') >>> p1 = plot(x**4,(x,10,20),label='$x^4$',show=False,legend=True) >>> p2 = plot(x,line_color='red',label='$x$',legend= True) >>> p1.extend(p2) >>> p1.show() 关键字

_backend