From 153def698d7341629f294f774f16c20c8a053d85 Mon Sep 17 00:00:00 2001 From: Congcong Cai Date: Tue, 21 Nov 2023 17:21:05 +0800 Subject: [PATCH] fix: diagnose when accessing setter only property (#2800) Co-authored-by: CountBleck --- src/resolver.ts | 13 ++++++++++++- tests/compiler/getter-setter-errors.json | 1 + tests/compiler/getter-setter-errors.ts | 6 +++++- 3 files changed, 18 insertions(+), 2 deletions(-) diff --git a/src/resolver.ts b/src/resolver.ts index d6177806bd..349cd47d5e 100644 --- a/src/resolver.ts +++ b/src/resolver.ts @@ -1363,7 +1363,18 @@ export class Resolver extends DiagnosticEmitter { } case ElementKind.Property: { // someInstance.prop let propertyInstance = target; - let getterInstance = assert(propertyInstance.getterInstance); // must have a getter + let getterInstance = propertyInstance.getterInstance; + if (!getterInstance) { + // In TS, getters without setters return `undefined`. Since AS doesn't have + // undefined, we instead diagnose it at compile time, but this isn't + // compatible with TS. + let setterInstance = assert(propertyInstance.setterInstance); + this.errorRelated( + DiagnosticCode.Property_0_only_has_a_setter_and_is_missing_a_getter, + targetNode.range, setterInstance.declaration.range, propertyInstance.name + ); + return null; + } let type = getterInstance.signature.returnType; let classReference = type.getClassOrWrapper(this.program); if (!classReference) { diff --git a/tests/compiler/getter-setter-errors.json b/tests/compiler/getter-setter-errors.json index 81e016bde0..21c80b71ce 100644 --- a/tests/compiler/getter-setter-errors.json +++ b/tests/compiler/getter-setter-errors.json @@ -2,6 +2,7 @@ "asc_flags": [ ], "stderr": [ + "AS229: Property 'm' only has a setter and is missing a getter.", "TS2808: Get accessor 'm2' must be at least as accessible as the setter.", "EOF" ] diff --git a/tests/compiler/getter-setter-errors.ts b/tests/compiler/getter-setter-errors.ts index dd2b191127..c714d2f843 100644 --- a/tests/compiler/getter-setter-errors.ts +++ b/tests/compiler/getter-setter-errors.ts @@ -1,3 +1,8 @@ +class UseNonExistedGetter { + set m(v: string) {} +} +new UseNonExistedGetter().m.toString(); + class GetSetWithoutDifferenceVisibility { public get m1(): i32 { return 1; @@ -9,7 +14,6 @@ class GetSetWithoutDifferenceVisibility { } public set m2(v: i32) {} } - new GetSetWithoutDifferenceVisibility().m1; // m1 is valid new GetSetWithoutDifferenceVisibility().m2; // m2 is invalid