From 4f15024d3066c36e4c02ddc0bad91c24d5faf1ba Mon Sep 17 00:00:00 2001 From: Congcong Cai Date: Wed, 15 Nov 2023 08:45:52 +0800 Subject: [PATCH] fix: add diagnose when initializing field in interface (#2797) --- src/diagnosticMessages.json | 1 + src/program.ts | 4 ++++ tests/compiler/interface-with-initializer.json | 7 +++++++ tests/compiler/interface-with-initializer.ts | 9 +++++++++ 4 files changed, 21 insertions(+) create mode 100644 tests/compiler/interface-with-initializer.json create mode 100644 tests/compiler/interface-with-initializer.ts diff --git a/src/diagnosticMessages.json b/src/diagnosticMessages.json index e15946207a..3ff9e9f162 100644 --- a/src/diagnosticMessages.json +++ b/src/diagnosticMessages.json @@ -119,6 +119,7 @@ "Decorators are not valid here.": 1206, "'abstract' modifier can only appear on a class, method, or property declaration.": 1242, "Method '{0}' cannot have an implementation because it is marked abstract.": 1245, + "An interface property cannot have an initializer.": 1246, "A definite assignment assertion '!' is not permitted in this context.": 1255, "A class may only extend another class.": 1311, "A parameter property cannot be declared using a rest parameter.": 1317, diff --git a/src/program.ts b/src/program.ts index 1f9849eec2..3174be4875 100644 --- a/src/program.ts +++ b/src/program.ts @@ -2671,6 +2671,10 @@ export class Program extends DiagnosticEmitter { /** Parent interface. */ parent: InterfacePrototype ): void { + let initializer = declaration.initializer; + if (initializer) { + this.error(DiagnosticCode.An_interface_property_cannot_have_an_initializer, initializer.range); + } let typeNode = declaration.type; if (!typeNode) typeNode = Node.createOmittedType(declaration.name.range.atEnd); this.initializeProperty( diff --git a/tests/compiler/interface-with-initializer.json b/tests/compiler/interface-with-initializer.json new file mode 100644 index 0000000000..be54c01a3f --- /dev/null +++ b/tests/compiler/interface-with-initializer.json @@ -0,0 +1,7 @@ +{ + "asc_flags": [ + ], + "stderr": [ + "TS1246: An interface property cannot have an initializer." + ] +} diff --git a/tests/compiler/interface-with-initializer.ts b/tests/compiler/interface-with-initializer.ts new file mode 100644 index 0000000000..c1d5689042 --- /dev/null +++ b/tests/compiler/interface-with-initializer.ts @@ -0,0 +1,9 @@ +interface I { + v: string = ""; +} + +class C implements I { + v: string = ""; +} + +new C();