导入模块时如何扩展字符串原型?

How to extend string prototype when importing modules?

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

内部模块失败:

 /// <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'

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

这就是为什么如果您避免使用 import 语句它会起作用的原因 - 因为文件不会被算作一个模块 - 所以在任何模块之外声明您的 String 接口意味着它在gloabl 范围就像原来的 String 接口。