扩展Typescript中的内置类型 [英] Extending built-in types in Typescript

查看:540
本文介绍了扩展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中的内置类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆