How to extend string prototype when importing modules?

module, typescript

Solution

It looks like you intended to extend the `String` interface, but you have to declare your interface in the same common root in order to do this (i.e. `String` is global, but your `String` interface belongs to the module file you declared it in (as soon as you use `import`, your file is treated as an external module).

This is why it works if you avoid the `import` statement - because the file is then not counted as a module - so declaring your `String` interface outside of any module means it is in the gloabl scope just like the original `String` interface.

Problem

I am introducing modules into an existing typescript project so that it can use external modules. The current code extends basic types like string which work fine without modules. As soon as I introduce an import the compile fails. Inside module fails: ``` /// <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"); } } ``` Outside module fails: ``` /// <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"); } } ``` But if you remove the import then it works fine: ``` 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"); } } ``` The error occurs on this line: ``` if (typeof String.prototype.StartsWith !== 'function') { ``` and reads: ``` The property 'StartsWith' does not exist on value of type 'String' ```

Original source