我是一名帮助翻译文本的助手。
我在尝试使用Typescript扩展Lodash并添加自定义mixin时遇到了困难。
我的不成功尝试:
假设我使用mixin将一个新函数添加到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;
}
import _ from "lodash";
在其他文件中使用时,swap
函数不可用。
部分成功的尝试:
之后我寻求了帮助,并且人们建议使用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;
并使用以下新的混合:
//otherFile.ts
import _ from "./lodashMixins";
function someFn(){
var array = [1,2,3,4]
_.swap(array, 1, 2);
}
现在虽然可以正常工作,但是有两个问题:
- 首先,新的
swap
函数无法使用lodash的链式语法(明确链接和隐式链接都不行)。
这意味着,如果我执行以下任何操作,typescript都会报错:
//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[]>'.
}
- 我需要使用这个 丑陋的
import _ from "./lodashMixins";
而不是标准的import _ from "lodash";
。
请有人提供一个优雅的解决方案,可以提供typescript类型支持,同时进行链接,没有任何代码味道或丑陋。 谢谢。 :)
也许John-David Dalton可以帮忙。
LoDashImplicitWrapper
,以便TS正确地对_([1, 2, 3]).swap(0, 2).value()
进行类型标注。使用的版本为 TS v3.2.2 和 Lodash v4.17.11。 - tokland