Allow assignment to readonly parameter property within the constructor

This commit is contained in:
Andy Hanson 2016-05-20 08:54:05 -07:00
parent f95f51fefc
commit dcbaadaa60
5 changed files with 63 additions and 2 deletions

View file

@ -11882,8 +11882,18 @@ namespace ts {
if (symbol.flags & SymbolFlags.Property &&
(expr.kind === SyntaxKind.PropertyAccessExpression || expr.kind === SyntaxKind.ElementAccessExpression) &&
(expr as PropertyAccessExpression | ElementAccessExpression).expression.kind === SyntaxKind.ThisKeyword) {
const func = getContainingFunction(expr);
return !(func && func.kind === SyntaxKind.Constructor && func.parent === symbol.valueDeclaration.parent);
return !isInConstructor(getContainingFunction(expr));
function isInConstructor(func: FunctionLikeDeclaration) {
if (!func)
return false;
if (func.kind !== SyntaxKind.Constructor)
return false;
if (func.parent === symbol.valueDeclaration.parent) // If the symbol was declared in the class:
return true;
if (func === symbol.valueDeclaration.parent) // If symbolDecl is a parameter property of the constructor:
return true;
return false;
}
}
return true;
}

View file

@ -0,0 +1,16 @@
//// [readonlyConstructorAssignment.ts]
class A {
constructor(readonly x: number) {
this.x = 7;
}
}
//// [readonlyConstructorAssignment.js]
var A = (function () {
function A(x) {
this.x = x;
this.x = 7;
}
return A;
}());

View file

@ -0,0 +1,14 @@
=== tests/cases/conformance/classes/constructorDeclarations/constructorParameters/readonlyConstructorAssignment.ts ===
class A {
>A : Symbol(A, Decl(readonlyConstructorAssignment.ts, 0, 0))
constructor(readonly x: number) {
>x : Symbol(A.x, Decl(readonlyConstructorAssignment.ts, 1, 16))
this.x = 7;
>this.x : Symbol(A.x, Decl(readonlyConstructorAssignment.ts, 1, 16))
>this : Symbol(A, Decl(readonlyConstructorAssignment.ts, 0, 0))
>x : Symbol(A.x, Decl(readonlyConstructorAssignment.ts, 1, 16))
}
}

View file

@ -0,0 +1,16 @@
=== tests/cases/conformance/classes/constructorDeclarations/constructorParameters/readonlyConstructorAssignment.ts ===
class A {
>A : A
constructor(readonly x: number) {
>x : number
this.x = 7;
>this.x = 7 : number
>this.x : number
>this : this
>x : number
>7 : number
}
}

View file

@ -0,0 +1,5 @@
class A {
constructor(readonly x: number) {
this.x = 7;
}
}