2

Anybody knows how to extend a base class in Typescript 1.7. Something like this example in JS:

String.prototype.foo = function() {
    return 'Bar';
}

I found many ways to do this in older versions of Typescript, like:

interface String {
    foo(): string;
}

String.prototype.foo= function() {
    return 'Bar';
}

or

interface StringConstructor {
    foo(): string;
}

String.foo = function() {
    return 'Bar';
}

I tried many ways to do this, but I aways get error while TS is compiled!

Thank you

Felipe

3
  • Possible duplicate of this question. Commented Dec 8, 2015 at 15:58
  • Are you using external modules? What's the error you get? If you are using external modules then you need to move the interface into a definition file. Commented Dec 8, 2015 at 17:01
  • You are right David.. Thank you!! Commented Dec 9, 2015 at 10:46

1 Answer 1

1

The following still works in action:

interface String {
    foo(): string;
}

String.prototype.foo= function() {
    return 'Bar';
}

You probably have it in an external module which disconnects it from the global context. More on this : https://basarat.gitbooks.io/typescript/content/docs/types/lib.d.ts.html

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

2 Comments

The unique trick is interface definition should be in a definition file.
It works but produces the following error: TS2339: Property 'foo' does not exist on type 'String' in typescript 1.8

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.