Can `this` be used when specifying a default value in typescript?

Is this in scope in the method parameter list in TypeScript?

Consider the following code :

 class Foo { constructor(public name) {} bar(str: string = this.name) { console.log(str); } } let f = new Foo("Yo"); f.bar(); 

The default value of str specified using this , although we are not inside the body of the instance method.

Currently (in typescript 1.8) this works as it translates to:

 Foo.prototype.bar = function (str) { if (str === void 0) { str = this.name; } console.log(str); }; 

So, this used inside the method, but is it listed as legal?

I could not find an answer to this with a cursory glance at the specification .

Note. . This is not legal in C ++ , which makes me wonder if this is a supposed function or just an artifact of the transpilation process.

+6
source share
2 answers

Section 8.3.1 of the Designer Parameters explicitly states that using the this expression in the default constructor is an error.

Section 8.4.2 Declaring function functions does not mention any errors in using this in the default expressions in the regular class methods (non-constructors).

Section 6.6 Code Generation finally explains that the code is generated as:

 if (<Parameter> === void 0) { <Parameter> = <Default>; } 

Where parameter is the name of the parameter and the default is the default.

In other words, the current specification explicitly allows the use of this in expressions of the default value of a parameter, with the exception of the constructor.

Your code works perfectly according to the specification.

+4
source

Yes. It is valid in accordance with the EcmaScript 6 specification , and the TypeScript transporter should consider it as such,

Since the default arguments are evaluated during the conversation, you can even use method calls and other arguments in the default value.

+4
source

All Articles