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

daw*_*daw 6 module typescript

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

内部模块失败:

 /// <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"); }
 }
Run Code Online (Sandbox Code Playgroud)

外部模块失败:

 /// <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"); }
 }
Run Code Online (Sandbox Code Playgroud)

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

 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"); }
 }
Run Code Online (Sandbox Code Playgroud)

错误发生在这一行:

if (typeof String.prototype.StartsWith !== 'function') {
Run Code Online (Sandbox Code Playgroud)

并写道:

The property 'StartsWith' does not exist on value of type 'String'
Run Code Online (Sandbox Code Playgroud)

Fen*_*ton 5

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

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