【发布时间】:2018-10-01 05:28:59
【问题描述】:
当我尝试使用我的自定义 mixins 扩展 lodash 时,我在使用带有 typescript 的 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;
}
如果我在其他文件中import _ from "lodash";,_ 上的函数swap 不可用。
部分成功的尝试:
然后我寻找help, and people suggested 到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 的链式语法(无论是显式链式还是隐式链式)。
这意味着,如果我执行以下任何操作,打字稿就会生气:
//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 可以帮忙。
【问题讨论】:
标签: javascript typescript lodash mixins chaining