我需要在字符串类上有一些全局原型(prototype)函数。例如。
string.prototype.trimWhiteSpaces = function () {
return this.replace(/ +/g, '');
}
我正在使用 Angular CLI,我希望我的 Angular 4 应用程序中的所有字符串都可以访问此函数。我已将代码片段添加到名为 prototypes.js
的文件中,并在 .angular-cli.json
中加载了该文件
"scripts": [
"assets/js/prototypes.js",
"../node_modules/jquery/dist/jquery.min.js",
"../node_modules/bootstrap/dist/js/bootstrap.min.js",
"../node_modules/moment/min/moment.min.js"
],
但是,当我编译我的项目时,我不断收到以下错误
Property 'trimWhiteSpaces' does not exist on type 'string'.
我如何使这些功能在我的应用程序中可访问
最佳答案
问题是 TypeScript 不知道这些类型定义。
快速方法
为您正在使用的每个方法提供定义
打开 typings.d.ts 并添加以下内容:
interface String {
trimWhiteSpaces: () => string;
}
您必须为正在使用的每个 函数提供定义。虽然速度更快,但现在可能是重新评估 prototypes.js
并使其对 TypeScript 友好的好时机。
专业方法
将库转换为 typescript 并根据需要导入/导出函数。这会耗费更多时间,但如果您拥有图书馆,这将是您最终想要做的事情。
如果你想更新库并仍然使用原型(prototype)(它没有很好地摇动)你会做这样的事情:
文件:string-prototypes.ts
String.prototype.trimWhiteSpaces = trimWhiteSpaces;
interface String {
trimWhiteSpaces: typeof trimWhiteSpaces;
}
function trimWhiteSpaces() {
return this.split(' ').join('');
}
在您的 app.module.ts
的顶部,像这样导入此文件:
import './string-prototypes';
第二种方法是像这样构建您的库,并根据需要导入函数。
文件:string-helpers.ts
export function trimWhiteSpaces(input: string) {
return input.split(' ').join('');
}
在组件中:
import { trimWhiteSpaces } from './string-helpers';
您以这种方式失去了原型(prototype)扩充,但它保证您的库的消费者只使用他们需要的东西。
关于javascript - Angular CLI - 如何在整个应用程序中共享原型(prototype)函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47065569/