扩展Typescript中的内置类型

编程入门 行业动态 更新时间:2024-10-06 06:41:48
本文介绍了扩展Typescript中的内置类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我具有以下结构:

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显示错误消息.

I try to extend the string's prototype with a function. I tried so far a lot of way, I found on several sites. But either the tsc gives me error, or the PHPStorm shows error message.

// 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显示以下错误:

I added the augmentation for the String class to the d.ts file. Then I define the body of the function in a separate file. When I implement it in the src/Extensions/string.ts file, the tsc command gives no error message, BUT the PHPStorm shows the following error:

TS2339: Property 'myCustomFn' does not exist on type 'String'.

此外,在代码的任何地方,自动完成都会显示我的方法,甚至代码也可以执行,并使用myCustomFn函数.

Moreover, anywhere in the code the auto-completition shows my method, and even the code can be executed, and uses the myCustomFn function.

问题:

  • 这仅仅是IDE的错误吗?
  • 我是在做错什么还是应该以不同的方式扩展String类?
推荐答案

Github 上的完整示例

将String接口扩展名放置在随机的.d.ts文件中:

Place your String interface extension in a random .d.ts file:

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

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

Add another file extension.ts where you add the prototype:

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

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

Then import the extension.ts file into your root index.ts file:

import './extension';

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

Now you can add your String().myCustomFn(text: string); everywhere you want.

P.S.重要的是,将.d.ts文件包含在编译文件中. typeRoots属性不是必需的.

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" ] }

更多推荐

扩展Typescript中的内置类型

本文发布于:2023-11-28 06:20:28,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1641268.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:类型   Typescript

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!