0

A library I'm working with adds secondary functionality to JSON.parse, which is of course a built-in method on a built-in object (but writable). I need to add the following overload signature to let the TypeScript compiler know about the new functionality:

<T>(text: string, type: { new (): T }) => T

Obviously, I would refrain from touching lib.d.ts.

I tried redeclaring the entire JSON interface, as well as making the global JSON variable of that type, but that duplicated all built-in call signatures besides adding the new one.

If I redeclare the JSON interface with just the new signature, the whole thing seems to work correctly, the new method overload is accepted along with the built-in ones, but this just seems hackish and fragile:

declare interface JSON {
    parse<T>(text: string, type: { new (): T }): T;
}

declare var JSON: JSON;

How do I correctly extend a built-in object with a method overload?

1 Answer 1

3

Create a file globals.d.ts and just put in the following :

declare interface JSON {
    parse<T>(text: string, type: { new (): T }): T;
}

Now you can use this JSON.parse overload in yourfile.ts.

More

https://basarat.gitbooks.io/typescript/content/docs/types/lib.d.ts.html

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

Comments

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.