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

Module 导入模块时如何扩展字符串原型?,module,typescript,Module,Typescript,我将模块引入到现有的typescript项目中,以便它可以使用外部模块。当前的代码扩展了基本类型,如string,它在没有模块的情况下可以正常工作。我一引入导入,编译就失败了 模块内部故障: /// <reference path='../defs/react.d.ts' /> import React = require("react"); module ExampleModule { interface String { StartsWith

我将模块引入到现有的typescript项目中,以便它可以使用外部模块。当前的代码扩展了基本类型,如string,它在没有模块的情况下可以正常工作。我一引入导入,编译就失败了

模块内部故障:

 /// <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"); }
 }
错误发生在这一行:

if (typeof String.prototype.StartsWith !== 'function') {
全文如下:

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

看起来您打算扩展
字符串
接口,但是您必须在同一个公共根中声明您的接口才能这样做(即
字符串
是全局的,但您的
字符串
接口属于您在其中声明的模块文件)(只要您使用
导入
,您的文件就会被视为一个外部模块)


这就是为什么如果您避免使用
import
语句,它会起作用的原因,因为该文件不会被视为模块,因此在任何模块之外声明
String
接口意味着它与原始
String
接口一样位于gloabl范围内。

谢谢。我发现typescript处理模块的方式非常混乱ng(内部、外部、带导入、不带导入、commonjs、amd等)。在我所知的任何其他语言中,类似导入的语句都不会改变单元的编译方式。这可能会让人困惑——有人建议将内部模块更改为“名称空间”,以帮助实现这一点,所以请关注此空间。
The property 'StartsWith' does not exist on value of type 'String'