如何使用Typescript 2.0扩展underscore

12 浏览
0 Comments

如何使用Typescript 2.0扩展underscore

我有以下代码片段来扩展underscore的sum函数\n

//underscore.extension.ts
import * as _ from "underscore"
declare module "underscore" {
    export interface UnderscoreStatic {
        sum(items: number[]): number;
    }
}
_.mixin({
    sum: items => { return _.reduce(items, function (s, x) { return s + x; }, 0); }
});

\n然而,使用_.sum()会给我一个\"属性\'sum\'在类型\'UnderscoreStatic\'上不存在\"的错误。请问有人能告诉我正确的做法吗?

0
0 Comments

如何使用Typescript 2.0扩展underscore

在使用Typescript编写项目时,需要先声明相应的定义,而sum()方法并未被识别。你是否尝试将underscore扩展为一个类,并将sum声明为静态方法?然后将新扩展的underscore类导出,以便在整个应用程序中使用?

但是,underscore本身并没有构造函数,因此你需要扩展接口并混合你的更改,并返回新的接口,代码如下所示:

import * as _ from 'underscore';
interface UnderscoreExtended extends UnderscoreStatic {
    sum(items: number[]): number;
}
_.mixin({
    sum: items => { return _.reduce(items, function (s, x) { return s + x; }, 0); }
});
export { UnderscoreExtended } // as UnderscoreStatic }
export default _ as UnderscoreExtended;

在你的项目中,你可以导入这个扩展的underscore,并像平常一样使用它:

import _ from '';
_.isNumber(
    _.sum([1, 2])
);

我实际上是参考了在1.8版本中声明的“从模块扩展全局/模块范围”来扩展underscore的。我想我在这里有一些误解。如果有伪代码,那将是非常有帮助的。

这样做是可行的,但并不完全符合我的预期。我想确认一下,是否不可能只导入underscore本身,而不是扩展后的underscore,以使用扩展的underscore方法?

我能想到的唯一办法是修改你在项目中包含的underscore的声明文件(d.ts)。

解决方法:修改underscore的声明文件(d.ts)来包含扩展的方法。

0
0 Comments

问题的出现原因是无法将自定义的函数混入到Underscore库中,即使按照官方文档中的方法进行了全局扩展。解决方法是使用Typescript的全局增强功能,通过声明全局接口并将自定义函数混入到Underscore库中。

具体的解决方法如下:

首先,导入Underscore库:

import * as _ from "underscore"

然后,声明一个全局接口,并在该接口中添加自定义函数:

declare global {
    interface UnderscoreStatic {
        sum(items: number[]): number;
    }
}

接下来,使用_.mixin()方法将自定义函数混入到Underscore库中:

_.mixin({
    sum: items => { return _.reduce(items, function (s, x) { return s + x; }, 0); }
});

需要注意的是,由于自定义函数的混入必须至少运行一次,所以需要在程序早期包含/引入这个修改。但在混入后,可以像正常使用Underscore库一样使用它。

然而,尽管按照上述方法进行了全局增强的声明,但仍然可能会出现新混入的函数不被识别为UnderscoreStatic的一部分的问题。这可能是由于Typescript的版本变化导致的。可以尝试使用扩展和导入新的扩展来解决这个问题。

0