如何在TypeScript中使用lodash.mixin

Sma*_*boy 5 typescript lodash

我的团队正在评估从JavaScript中将部分文件切换为TypeScript,并且我们在代码中广泛使用了一些自定义mixin方法.从做一些基本的测试看来,虽然我们可以使用_.mixin按照规范创建mixins,但是我们不能在没有编译错误的情况下引用它们.当然,我们可以将这些引用放在定义文件中,但我通常不想修改它.

有什么方法可以做我们正在寻找的东西,还是我们运气不好?

Chr*_*ris 7

请参阅有关扩展内置类型的TypeScript 文档,我认为这也适用于此处。_被定义为var _: _.LoDashStatic,并且vars 当前不可扩展。

我发现公开扩展的最佳方法是通过lodash-mixins.ts定义新LoDashMixins接口 (extending LoDashStatic)、应用 mixins 并将导出_转换为自定义接口的脚本。这个例子定义了一个单一的 mixin,但我们的想法是将所有的 mixin 添加到一个脚本中以便于导入。

import * as _ from 'lodash';
import xdiff from './xdiff';

interface LoDashMixins extends _.LoDashStatic {
  xdiff<T>(array:T[], values:T[]): T[];
}

_.mixin({xdiff:xdiff});

export default <LoDashMixins>_;
Run Code Online (Sandbox Code Playgroud)

当您想使用 mixins 时,请使用 import'./lodash-mixins'而不是'lodash'. 您现在可以在编译时查看所有内置函数以及 mixin。

import _ from './lodash-mixins';

_.map([]); // built-in function still compiles
_.xdiff([], []); // mixin function compiles too
Run Code Online (Sandbox Code Playgroud)


Bla*_*wen 5

你可以这样做。

// somewhere in your project
declare module _ {
    interface LoDashStatic {
        foo(value: string): number;
    }
}

// extend it somewhere else 
declare module _ {
    interface LoDashStatic {
        bar(value: number);
    }
}
Run Code Online (Sandbox Code Playgroud)

测试一下


Sma*_*boy 1

目前看来,我想要的东西似乎无法毫无痛苦地获得。相反,我必须修改 lodash.d.ts 文件以包含我想要的定义,类似于以下内容:

declare module _ {
    // Default methods declared here...

    //*************************************************************************
    // START OF MIXINS, THESE ARE NOT PART OF LODASH ITSELF BUT CREATED BY US!
    //*************************************************************************

    interface LoDashStatic {
        isNonEmptyString: (str: string) => boolean;
        isEmptyString: (str: string) => boolean;
        isEmptyArray: (a: any[]) => boolean;
        isNonEmptyArray: (a: any[]) => boolean;
        isNullOrEmptyString: (str: string) => boolean;
        isNullOrUndefined: (val: any) => boolean;
        isNullOrEmpty(value: any[]): boolean;
        isNullOrEmpty(value: _.Dictionary<any>): boolean;
        isNullOrEmpty(value: string): boolean;
        isNullOrEmpty(value: any): boolean;
    }

    //*************************************************************************
    // END OF MIXINS
    //*************************************************************************

    // Default types declared here...
}
Run Code Online (Sandbox Code Playgroud)

我讨厌修改默认文件,但这似乎是较小的弊端。