Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Is this in scope in the parameter list of a method 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 is specified using this even though we're not inside an instance method's body.

Currently (in typescript 1.8) this works since it's transpiled to:

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

So this is used inside the method but is this specified to be legal?

I couldn't find an answer to this with a cursory glance at the specification.

Note: This isn't legal in C++ which makes me question whether it's an intended feature or just an artefact of the transpilation process.

like image 938
Motti Avatar asked Jun 22 '16 08:06

Motti


2 Answers

In the section 8.3.1 Constructor Parameters it is explicitly stated that using this in constructor parameter default value expressions is an error.

In the section 8.4.2 Member Function Declarations there is no mention of any errors of using this in default value expressions in ordinary class methods (non-constructors).

Section 6.6 Code Generation finally explains that the code is generated in the form of:

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

Where Parameter is the parameter name and Default is the default value expression.

In other words, current specification explicitly allows using this in parameter default value expressions, except in constructor.

Your code is perfectly valid according to spec.

like image 66
zlumer Avatar answered Sep 18 '22 10:09

zlumer


Yes. It is valid according to EcmaScript 6 specification and the TypeScript transpiler should treat it as such.

As default arguments are evaluated at call time, you can even use method calls and other arguments in the default value.

like image 37
Tomas Nikodym Avatar answered Sep 20 '22 10:09

Tomas Nikodym