This project is read-only.


Adding properties through .prototype


Adding properties through .prototype.<value> = … breaks the type analysis.
What I expected it to do was to understand that I'm adding a property to the prototype,
and therefore I expected it to understand what type this was, in the context.

Instead, it refuses to perform any type analysis (and infers any everywhere).
It also raises a warning saying that the property I'm adding doesn't exist on the prototype (duh).

At least, it still compiles to JS just fine!
Closed Mar 25, 2013 at 5:38 PM by RyanCavanaugh
We will not be automatically inferring type data from .prototype assignments


billti wrote Oct 1, 2012 at 10:30 PM

Interfaces are open ended, so you can extend the Math interface to include your additions. For example,

interface Math {
qsort: (input: Array) => Array;

var x = Math.qsort([1,4,2]);

This should compile without any issue via tsc on the command line. Note however that the Math interface is defined in lib.d.ts. This is treated specially by the language service in VS, and simply extending types defined within it causes issues currently. The solution is to copy the lib.d.ts out of the install location ("C:\Program Files (x86)\Microsoft SDKs\TypeScript\") and into your project, and then just reference it there, i.e. your final code would look like:

/// <reference path="lib.d.ts"/>

interface Math {
qsort: (input: Array) => Array;
var x = Math.qsort([1,3,2]);

(Of course if you're copying lib.d.ts to your project locally - you could also modify the type in there).

Let me know if this resolves your issue.

espadrine wrote Oct 2, 2012 at 7:15 AM

It does work, but I'm not trying to modify the Math interface ?

There are many ways to implement qsort,
including just writing the function with an array as a parameter.
Unless modifying the prototype is not allowed
(in which case it shouldn't compile at all, but that would be a shame),
it feels unfortunate that the type analysis fails to provide cues when we do.

(Of course, there is the other issue that Array::filter doesn't return an Array,
which the type system seems furious about. Never mind that;
I guess it would need re-implementing that function to make it happy.)