【问题标题】:Extending built-in types in Typescript在 Typescript 中扩展内置类型
【发布时间】:2019-10-07 08:33:58
【问题描述】:

我有以下结构:

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 类?

【问题讨论】:

    标签: javascript typescript webdriver-io typescript3.0 ts-node


    【解决方案1】:

    Github 上的完整工作示例

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

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

    在您添加prototype 的位置添加另一个文件extension.ts

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

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

    import './extension';
    

    现在您可以在任何地方添加您的String().myCustomFn(text: string);


    附:将.d.ts 文件包含 到编译文件中很重要。 typeRoots 属性不是必需的。

    tsconfig.json:

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

    【讨论】:

    • 就是这样。我做同样的事情。有一个.d.ts 文件——我在其中用一个函数扩展了原型。在另一个文件中,我编写了该函数的实现。在初始化代码时,我需要该文件。我提供了有关我的文件的更多信息。顺便说一句:这是一个 webdriver-io 项目。在before 回调中,我需要该文件。并且代码运行。我不明白为什么 IDE 将其标记为错误。
    猜你喜欢
    • 2018-10-06
    • 2021-06-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-14
    • 2018-05-08
    • 1970-01-01
    相关资源
    最近更新 更多