16

how does one augment one of the 'built-in' types? eg Array?

In JS, I'd do something like

Array.prototype.shuffle = function () { ... };

what's the equivalent in TypeScript?

1 Answer 1

19

Types are 'open ended' in TypeScript, so you can just write:

interface Array {
  shuffle: () => any; // <-- Whatever signature you want.
}

And then the type is expanded to include the new function (and you can assign a function matching the signature to it).

Note however that extending the built-in types (those in lib.d.ts - such as Array) has an issue currently in the language service, as it caches those internally for perf reasons. Do the workaround I wrote-up at http://typescript.codeplex.com/workitem/4 to extend the built-in types without errors in the language service in VS.

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

3 Comments

Can we have the link to the work-around updated pls?
Or just typed into the answer where it should be?
Hey all, found the answer on the WayBack Machine! web.archive.org/web/20180115225023/http://…

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.