【问题标题】:How to extend string prototype when importing modules?导入模块时如何扩展字符串原型?
【发布时间】:2015-02-28 08:19:15
【问题描述】:

我正在将模块引入现有的打字稿项目,以便它可以使用外部模块。当前代码扩展了基本类型,如字符串,无需模块即可正常工作。一旦我引入导入,编译就会失败。

内部模块失败:

 /// <reference path='../defs/react.d.ts' />

 import React = require("react");

 module ExampleModule {
     interface String {
         StartsWith: (str : string) => boolean;
     }

     if (typeof String.prototype.StartsWith !== 'function') {
          String.prototype.StartsWith = function(str) {
               return this.slice(0, str.length) === str;
          };
     }

     export function foo() { return "sdf".StartsWith("s"); }
 }

外部模块失败:

 /// <reference path='../defs/react.d.ts' />

 import React = require("react");

 interface String {
     StartsWith: (str : string) => boolean;
 }

 if (typeof String.prototype.StartsWith !== 'function') {
      String.prototype.StartsWith = function(str) {
           return this.slice(0, str.length) === str;
      };
 }

 module ExampleModule {
    export function foo() { return "sdf".StartsWith("s"); }
 }

但如果你删除导入,那么它工作正常:

 interface String {
     StartsWith: (str : string) => boolean;
 }

 if (typeof String.prototype.StartsWith !== 'function') {
      String.prototype.StartsWith = function(str) {
           return this.slice(0, str.length) === str;
      };
 }

 module ExampleModule {
    export function foo() { return "sdf".StartsWith("s"); }
 }

错误发生在这一行:

if (typeof String.prototype.StartsWith !== 'function') {

并阅读:

The property 'StartsWith' does not exist on value of type 'String'

【问题讨论】:

    标签: module typescript


    【解决方案1】:

    看起来您打算扩展String 接口,但您必须在相同的公共根中声明您的接口才能执行此操作(即String 是全局的,但您的String 接口属于您在其中声明它的模块文件(一旦您使用import,您的文件就会被视为外部模块)。

    这就是为什么如果你避免使用import 语句它会起作用的原因——因为该文件不被视为一个模块——所以在任何模块之外声明你的String 接口意味着它在全局范围内,就像原来的一样String接口。

    【讨论】:

    • 谢谢。我发现 typescript 处理模块的方式非常令人困惑(内部、外部、导入、不导入、commonjs、amd 等)。在我所知道的其他语言中,import like 语句不会改变单元的编译方式。
    • 这可能会造成混淆 - 有人提议将内部模块更改为“命名空间”以帮助解决这个问题,所以请注意这个空间。
    猜你喜欢
    • 2014-07-28
    • 2021-01-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-08
    • 2022-12-11
    • 1970-01-01
    • 2019-05-27
    相关资源
    最近更新 更多