gpt4 book ai didi

javascript - 在 Typescript 中扩展内置类型

转载 作者:行者123 更新时间:2023-11-29 22:46:43 28 4
gpt4 key购买 nike

我有以下结构:

project
|- types
|- global.d.ts
|- string.d.ts
|- wdio.d.ts
|- src
|- Models
|- Resources
|- Components
|- Extensions
|- string.ts
|- ...
|- tsconfig.json
|- wdio.conf.js

我尝试用函数扩展字符串的原型(prototype)。到目前为止,我尝试了很多方法,我在几个网站上找到了。但是 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:类型“String”上不存在属性“myCustomFn”。

此外,自动补全代码中的任何地方都显示了我的方法,甚至可以执行代码,并使用了myCustomFn函数。

问题:

  • 这只是 IDE 的错误吗?
  • 我是做错了什么,还是应该以不同的方式扩展 String 类?

最佳答案

关于 Github 的完整工作示例

将你的 String 接口(interface)扩展放在一个随机的 .d.ts 文件中:

interface String {
myCustomFn(text : string) : string;
}

添加另一个文件 extension.ts,在其中添加 prototype:

String.prototype.myCustomFn = function(text : string) : string {
return 'myCustomFn';
};

然后将 extension.ts 文件导入到您的根 index.ts 文件中:

import './extension';

现在您可以在任意位置添加 String().myCustomFn(text: string);


P.S. it is important that you include the .d.ts file to your compilation files. The typeRoots property is not necessary.

tsconfig.json:

{
"compilerOptions": {
"outDir": "dist"
},
"include": [
"src",
"types" // here is the .d.ts file
],
"exclude": [
"**/node_modules"
]
}

关于javascript - 在 Typescript 中扩展内置类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58265985/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com