0

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?

3
  • If you use the implicit return of type string from the call to format or declare the return type: var test:string =..., I don't see an error. Commented Mar 16, 2014 at 0:01
  • 1
    You've changed it to be an interface called String in a module test which would be different from the global type now. Commented Mar 16, 2014 at 2:18
  • thanks. I am new to typescript, and didn't know String is a type defined as builtin. Now, it make sense. thanks for your help. Commented Mar 16, 2014 at 3:12

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

3 Comments

thanks. how does this work.where does it say string (native type) implements "String".
ok, I saw the section 3.2.3 The String Type in the spec. I didn't know String was more than a random name. :-)
Also see : typescript.codeplex.com/workitem/810 what I asked a long time ago :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.