bsr
bsr

Reputation: 58662

typescript. defining an addition to prototype

One of the external library I use add a format method to string prototype.but, I cannot use it.

error TS2094: The property 'format' does not exist on value of type 'string'.

I defined an interface for this type.

 interface String {
        format : (any) => string;
    }

and tried like

var test:String =  "test".format({});

which gives error

error TS2012: Cannot convert 'string' to 'String':

if I define the format method myself like

String.prototype.format = function (d:any) : string {
...
}

the error disappears. But, I don't want to define it myself, it is given by the external library. tried casting with <String>. didn't work. How to do this.

--

Edit:

@basarath showed how it works. But, this is the way I was using it. It doesn't work, if I define the interface within the module see

// interface String {
//        format:(any) => string;
//}
module test {
    interface String {
        format:(any) => string;
    }
    class Clazz {        
        constructor() {
            this.fn();
        }

        fn() {
            var url:string = "test".format({});
        }
    }
}

is it because the changes to string prototype would not be visible outside the module?

Upvotes: 0

Views: 866

Answers (1)

basarat
basarat

Reputation: 275839

The following code should just work

interface String {
    format : (any) => string;
}

var test:string =  "test".format({});

And indeed it does

Note that String is not the same as string :

var strObject = new String('foo');
var strValue = 'foo';

strValue = strObject; // Error

And the reason is the way javascript works. One is an object, the other is not:

enter image description here

Upvotes: 1

Related Questions