我有以下结构:
project
|- types
|- global.d.ts
|- string.d.ts
|- wdio.d.ts
|- src
|- Models
|- Resources
|- Components
|- Extensions
|- string.ts
|- ...
|- tsconfig.json
|- wdio.conf.js
我尝试用函数扩展字符串的原型。到目前为止我尝试了很多方法,我在几个网站上找到了。但无论是tsc
给我错误,或者 PHPStorm 显示错误消息。
// types/string.d.ts
declare interface String {
myCustomFn(text : string) : string;
}
// src/Extensions/string.ts
String.prototype.myCustomFn = function(text : string) : string {
// ... Logic
return 'myCustomFn';
};
// tsconfig.json
...
"typeRoots": ["./types/"],
"include": [
"./src/**/*.ts",
"./types"
]
...
// wdio.conf.js
...
before: function (capabilities, specs) {
require('ts-node').register({ files: true });
require('../extensions/String');
},
...
我添加了增强String
类到 d.ts 文件。然后我在一个单独的文件中定义函数的主体。当我在src/Extensions/string.ts
文件,该tsc
命令没有给出错误消息,但 PHPStorm 显示以下错误:
TS2339: Property 'myCustomFn' does not exist on type 'String'.
而且,代码中的任何位置自动完成都会显示我的方法,甚至代码可以执行,并使用myCustomFn
功能。
问题:
- 这只是IDE的错误吗?
- 我是否做错了什么,或者 String 类的扩展方式应该以不同的方式进行?
完整的工作示例Github
放置您的String
接口随机扩展.d.ts
file:
interface String {
myCustomFn(text : string) : string;
}
添加另一个文件extension.ts
在哪里添加prototype
:
String.prototype.myCustomFn = function(text : string) : string {
return 'myCustomFn';
};
然后导入extension.ts
文件到你的根目录index.ts
file:
import './extension';
现在您可以添加您的String().myCustomFn(text: string);
你想要的任何地方。
附:重要的是你include the .d.ts
文件到您的编译文件。
这typeRoots
财产不是必需的。
tsconfig.json
:
{
"compilerOptions": {
"outDir": "dist"
},
"include": [
"src",
"types" // here is the .d.ts file
],
"exclude": [
"**/node_modules"
]
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)