parliament
parliament

Reputation: 22914

Typescript - modifying lib.d.ts

Let's say I want to add the following prototype to the String class.

String.prototype.beginsWith = function (string) {
     return(this.indexOf(string) === 0);
};

I need to add beginWith to lib.d.ts otherwise it won't complile:

declare var String: {
    new (value?: any): String;
    (value?: any): string;
    prototype: String;
    fromCharCode(...codes: number[]): string;
    //Here
}

The file is locked and I can't edit it.

I release I can just declare var String: any before the call but can I have it built in?

Upvotes: 1

Views: 1236

Answers (1)

Rajeesh
Rajeesh

Reputation: 4485

You don't need to modify the lib.d.ts instead extend the String interface first, then include the new method to the prototype chain of the object you wish to extend.

For e.g.

interface String {
   beginsWith(text: string): bool;
}

Then implement the new functionality and add it to the prototype chain

String.prototype.beginsWith = function (text) {
    return this.indexOf(text) === 0;
}

Now you will get the intellisense in the calling code and works as expected.

Upvotes: 6

Related Questions