joshstrike joshstrike - 3 years ago 165
TypeScript Question

Why does Typescript scope arrow notation to instances?

This is my 2nd day playing with Typescript, and I'm still trying to understand some of the intricacies of the syntax. I've looked around but not seen this asked in the same way before. So can anyone tell me why this is the case?

As far as I know, in the following code, fnA and fnB should be peers. And yet TS transcodes fnA into the constructor in Javascript, while fnB is defined in the prototype.

This seems to imply that classes which extend Sample cannot override fnA, just because it was written with arrow notation, yet they can still override fnB.

Phrased differently, it appears that using arrow notation in a class-level method in Typescript is equivalent to declaring that method final.

So: Why?

Is there some unspoken/idiomatic thing going on here where Typescript is basically saying if you want this function in the prototype, don't use arrow notation, otherwise if you're okay with a unique copy in every instance you can use it?

What is the actual logic TS uses to decide what goes in the prototype and what's copied to each instance?


class Sample {
public fnA: () => string =
() => { return ("Put this in the constructor"); };
public fnB():string {
return ("Put this in the prototype");

Transcodes to:

var Sample = (function () {
function Sample() {
this.fnA = function () { return ("Put this in the constructor"); };
Sample.prototype.fnB = function () {
return ("Put this in the prototype");
return Sample;

Answer Source

If this is really your 2nd day with TypeScript you should study simple examples first. Anyway, you might have given your code first and then paraphrase it.

What you are doing is:

  • you define a public property called fnA whose type is a parameterless string-valued function, and you initialize the property at the same time with an anonymous function of correct type.

  • you define a public method called fnB and give its implementation.

TS does not, as you say, "transcode fnA into the constructor".

Rather, TS does, what it always does, it builds a constructor in which all public, protected and private properties, which need initialization, are initialized to their proper values. There is no special logic at work, at all, and certainly no idiomatic thing. Hope, you like TypeScript.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download