如何使用带有链接支持的lodash和打字稿的mixins

pra*_*999 4 javascript mixins chaining typescript lodash

当我尝试使用我的自定义mixin扩展lodash时,我在使用Lodash时遇到问题.

我不成功的尝试:

假设我使用mixins为lodash添加一个新函数,如下所示:

//lodashMixins.ts

import * as _ from "lodash";

_.mixin({
  swap
});

function swap(array: Array<any>, index1: number, index2: number) {
    let temp = array[index1];
    array[index1] = array[index2];
    array[index2] = temp;
    return array;
}
Run Code Online (Sandbox Code Playgroud)

如果我在其他文件中,该功能swap不可用._import _ from "lodash";

部分成功的尝试:

于是我找了帮助,人们提出extend _.LoDashStatic,然后导出_作为新的扩展interface.

然后我做了以下事情:

//lodashMixins.ts

import * as _ from "lodash";

interface LodashExtended extends _.LoDashStatic {
  swap(array: Array<any>, index1: number, index2: number): Array<any>;
}

_.mixin({
  swap
});

function swap(array: Array<any>, index1: number, index2: number) {
    let temp = array[index1];
    array[index1] = array[index2];
    array[index2] = temp;
    return array;
}

export default _ as LodashExtended;
Run Code Online (Sandbox Code Playgroud)

并使用以下新的混合:

//otherFile.ts

import _ from "./lodashMixins";

function someFn(){
    var array = [1,2,3,4]
    _.swap(array, 1, 2);
}
Run Code Online (Sandbox Code Playgroud)

现在这个有效,但有两个问题:

  1. 首先,新swap函数不能使用lodash的链式语法(既不使用显式链接也不使用隐式链接).

这意味着,如果我执行以下任何操作,那打字稿就会生气:

//otherFile.ts

import _ from "./lodashMixins";

function someFn(){
    var cantDothis = _.chain([1,2,3,4]).map(x=>x*x).swap(1,2).value();
    //[ts] Property 'swap' does not exist on type 'LoDashExplicitWrapper<number[]>'.

    var neitherThis = _([1,2,3,4]).map(x=>x*x).swap(1,2).value();
    //[ts] Property 'swap' does not exist on type 'LoDashImplicitWrapper<number[]>'.
}
Run Code Online (Sandbox Code Playgroud)
  1. 其次,我必须做这个丑陋 import _ from "./lodashMixins";而不是标准import _ from "lodash";.

有人请提出一个优雅的解决方案,提供打字稿类型的支持,而链接没有任何代码气味或丑陋..谢谢.:)

可能是John-David Dalton可以提供帮助.

Tit*_*mir 9

您正在寻找模块扩充.您可以通过重新定义现有模块并添加额外方法来扩展现有模块中的接口.在这种情况下,您应该增加LoDashStatic静态使用和LoDashExplicitWrapper链使用.当您使用该模块时,您可以先导入lodash然后导入包含swap其副作用的模块(添加方法的副作用lodash)

// swap.ts
import * as _ from "lodash";


declare module "lodash" {
    interface LoDashStatic {
        swap<TValue>(array: Array<TValue>, index1: number, index2: number): TValue[];
    }
    interface LoDashExplicitWrapper<TValue> {
        swap(index1: number, index2: number): LoDashExplicitWrapper<TValue>;
    }
}

_.mixin({
    swap
});

function swap(array: Array<any>, index1: number, index2: number) {
    let temp = array[index1];
    array[index1] = array[index2];
    array[index2] = temp;
    return array;
}

//usage 
import * as _ from "lodash";
import "./swap"


console.log(_.chain([1,2,3,4]).map(x=>x*x).swap(1,2).map(x=> x * 2).value());

var array = [1,2,3,4]
console.log(  _.swap(array, 1, 2));
Run Code Online (Sandbox Code Playgroud)

您可以在此处阅读有关模块扩充的更多信息