Skip to content

Disallow uninitialised property overrides #33423

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 18 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 26 additions & 4 deletions src/compiler/checker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29443,7 +29443,6 @@ namespace ts {
}

function checkKindsOfPropertyMemberOverrides(type: InterfaceType, baseType: BaseType): void {

// TypeScript 1.0 spec (April 2014): 8.2.3
// A derived class inherits all members from its base class it doesn't override.
// Inheritance means that a derived class implicitly contains all non - overridden members of the base class.
Expand Down Expand Up @@ -29477,7 +29476,6 @@ namespace ts {
// type declaration, derived and base resolve to the same symbol even in the case of generic classes.
if (derived === base) {
// derived class inherits base without override/redeclaration

const derivedClassDecl = getClassLikeDeclarationOfSymbol(type.symbol)!;

// It is an error to inherit an abstract member without implementing it or being declared abstract.
Expand Down Expand Up @@ -29514,10 +29512,31 @@ namespace ts {
continue;
}

if (isPrototypeProperty(base) || base.flags & SymbolFlags.PropertyOrAccessor && derived.flags & SymbolFlags.PropertyOrAccessor) {
if (isPrototypeProperty(base)) {
// method is overridden with method or property/accessor is overridden with property/accessor - correct case
continue;
}
if (base.flags & SymbolFlags.PropertyOrAccessor && derived.flags & SymbolFlags.PropertyOrAccessor) {
const uninitialized = find(derived.declarations, d => d.kind === SyntaxKind.PropertyDeclaration && !(d as PropertyDeclaration).initializer);
if (uninitialized
&& !(base.valueDeclaration && base.valueDeclaration.parent.kind === SyntaxKind.InterfaceDeclaration)
&& !(derived.flags & SymbolFlags.Transient)
&& !(baseDeclarationFlags & ModifierFlags.Abstract)
&& !(derivedDeclarationFlags & ModifierFlags.Abstract)
&& !derived.declarations.some(d => d.flags & NodeFlags.Ambient)) {
const constructor = findConstructorDeclaration(getClassLikeDeclarationOfSymbol(type.symbol)!);
const propName = (uninitialized as PropertyDeclaration).name;
if ((uninitialized as PropertyDeclaration).exclamationToken
|| !constructor
|| !isIdentifier(propName)
|| !strictNullChecks
|| !isPropertyInitializedInConstructor(propName, type, constructor)) {
const errorMessage = Diagnostics.Property_0_will_overwrite_the_base_property_in_1_Add_a_declare_modifier_or_an_initializer_to_avoid_this;
error(getNameOfDeclaration(derived.valueDeclaration) || derived.valueDeclaration, errorMessage, symbolToString(base), typeToString(baseType));
}
}
continue;
}

let errorMessage: DiagnosticMessage;
if (isPrototypeProperty(base)) {
Expand Down Expand Up @@ -29583,6 +29602,9 @@ namespace ts {
}
const constructor = findConstructorDeclaration(node);
for (const member of node.members) {
if (getModifierFlags(member) & ModifierFlags.Ambient) {
continue;
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

do not require ! on declare x: number (since it is in fact not even allowed)

}
if (isInstancePropertyWithoutInitializer(member)) {
const propName = (<PropertyDeclaration>member).name;
if (isIdentifier(propName)) {
Expand Down Expand Up @@ -32507,7 +32529,7 @@ namespace ts {
else if (flags & ModifierFlags.Async) {
return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "async");
}
else if (isClassLike(node.parent)) {
else if (isClassLike(node.parent) && !isPropertyDeclaration(node)) {
return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_appear_on_a_class_element, "declare");
}
else if (node.kind === SyntaxKind.Parameter) {
Expand Down
12 changes: 12 additions & 0 deletions src/compiler/diagnosticMessages.json
Original file line number Diff line number Diff line change
Expand Up @@ -2204,6 +2204,10 @@
"category": "Error",
"code": 2609
},
"Property '{0}' will overwrite the base property in '{1}'. Add a 'declare' modifier or an initializer to avoid this.": {
"category": "Error",
"code": 2610
},
"Cannot augment module '{0}' with value exports because it resolves to a non-module entity.": {
"category": "Error",
"code": 2649
Expand Down Expand Up @@ -5144,6 +5148,14 @@
"category": "Message",
"code": 95093
},
"Prefix with 'declare'": {
"category": "Message",
"code": 95094
},
"Prefix all incorrect property declarations with 'declare'": {
"category": "Message",
"code": 95095
},

"No value exists in scope for the shorthand property '{0}'. Either declare one or provide an initializer.": {
"category": "Error",
Expand Down
12 changes: 10 additions & 2 deletions src/compiler/parser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5982,8 +5982,16 @@ namespace ts {
token() === SyntaxKind.NumericLiteral ||
token() === SyntaxKind.AsteriskToken ||
token() === SyntaxKind.OpenBracketToken) {

return parsePropertyOrMethodDeclaration(<PropertyDeclaration | MethodDeclaration>node);
const isAmbient = node.modifiers && some(node.modifiers, isDeclareModifier);
if (isAmbient) {
for (const m of node.modifiers!) {
m.flags |= NodeFlags.Ambient;
}
return doInsideOfContext(NodeFlags.Ambient, () => parsePropertyOrMethodDeclaration(node as PropertyDeclaration | MethodDeclaration));
}
else {
return parsePropertyOrMethodDeclaration(node as PropertyDeclaration | MethodDeclaration);
}
}

if (node.decorators || node.modifiers) {
Expand Down
34 changes: 34 additions & 0 deletions src/services/codefixes/addMissingDeclareProperty.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
/* @internal */
namespace ts.codefix {
const fixId = "addMissingDeclareProperty";
const errorCodes = [
Diagnostics.Property_0_will_overwrite_the_base_property_in_1_Add_a_declare_modifier_or_an_initializer_to_avoid_this.code,
];

registerCodeFix({
errorCodes,
getCodeActions: (context) => {
const changes = textChanges.ChangeTracker.with(context, t => makeChange(t, context.sourceFile, context.span.start));
if (changes.length > 0) {
return [createCodeFixAction(fixId, changes, Diagnostics.Prefix_with_declare, fixId, Diagnostics.Prefix_all_incorrect_property_declarations_with_declare)];
}
},
fixIds: [fixId],
getAllCodeActions: context => {
const fixedNodes = new NodeSet();
return codeFixAll(context, errorCodes, (changes, diag) => makeChange(changes, diag.file, diag.start, fixedNodes));
},
});

function makeChange(changeTracker: textChanges.ChangeTracker, sourceFile: SourceFile, pos: number, fixedNodes?: NodeSet<Node>) {
const token = getTokenAtPosition(sourceFile, pos);
if (!isIdentifier(token)) {
return;
}
const declaration = token.parent;
if (declaration.kind === SyntaxKind.PropertyDeclaration &&
(!fixedNodes || fixedNodes.tryAdd(declaration))) {
changeTracker.insertModifierBefore(sourceFile, SyntaxKind.DeclareKeyword, declaration);
}
}
}
6 changes: 2 additions & 4 deletions src/services/services.ts
Original file line number Diff line number Diff line change
Expand Up @@ -339,7 +339,6 @@ namespace ts {
}

class TokenObject<TKind extends SyntaxKind> extends TokenOrIdentifierObject implements Token<TKind> {
public symbol!: Symbol;
public kind: TKind;

constructor(kind: TKind, pos: number, end: number) {
Expand All @@ -349,9 +348,8 @@ namespace ts {
}

class IdentifierObject extends TokenOrIdentifierObject implements Identifier {
public kind!: SyntaxKind.Identifier;
public kind: SyntaxKind.Identifier = SyntaxKind.Identifier;
public escapedText!: __String;
public symbol!: Symbol;
public autoGenerateFlags!: GeneratedIdentifierFlags;
_primaryExpressionBrand: any;
_memberExpressionBrand: any;
Expand Down Expand Up @@ -541,7 +539,7 @@ namespace ts {
}

class SourceFileObject extends NodeObject implements SourceFile {
public kind!: SyntaxKind.SourceFile;
public kind: SyntaxKind.SourceFile = SyntaxKind.SourceFile;
public _declarationBrand: any;
public fileName!: string;
public path!: Path;
Expand Down
1 change: 1 addition & 0 deletions src/services/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@
"codefixes/addConvertToUnknownForNonOverlappingTypes.ts",
"codefixes/addMissingAwait.ts",
"codefixes/addMissingConst.ts",
"codefixes/addMissingDeclareProperty.ts",
"codefixes/addMissingInvocationForDecorator.ts",
"codefixes/addNameToNamelessParameter.ts",
"codefixes/annotateWithTypeFromJSDoc.ts",
Expand Down
8 changes: 7 additions & 1 deletion tests/baselines/reference/apparentTypeSubtyping.errors.txt
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
tests/cases/conformance/types/typeRelationships/apparentType/apparentTypeSubtyping.ts(10,5): error TS2416: Property 'x' in type 'Derived<U>' is not assignable to the same property in base type 'Base<string>'.
Type 'String' is not assignable to type 'string'.
'string' is a primitive, but 'String' is a wrapper object. Prefer using 'string' when possible.
tests/cases/conformance/types/typeRelationships/apparentType/apparentTypeSubtyping.ts(10,5): error TS2610: Property 'x' will overwrite the base property in 'Base<string>'. Add a 'declare' modifier or an initializer to avoid this.
tests/cases/conformance/types/typeRelationships/apparentType/apparentTypeSubtyping.ts(20,5): error TS2610: Property 'x' will overwrite the base property in 'Base2'. Add a 'declare' modifier or an initializer to avoid this.


==== tests/cases/conformance/types/typeRelationships/apparentType/apparentTypeSubtyping.ts (1 errors) ====
==== tests/cases/conformance/types/typeRelationships/apparentType/apparentTypeSubtyping.ts (3 errors) ====
// subtype checks use the apparent type of the target type
// S is a subtype of a type T, and T is a supertype of S, if one of the following is true, where S' denotes the apparent type (section 3.8.1) of S:

Expand All @@ -18,6 +20,8 @@ tests/cases/conformance/types/typeRelationships/apparentType/apparentTypeSubtypi
!!! error TS2416: Property 'x' in type 'Derived<U>' is not assignable to the same property in base type 'Base<string>'.
!!! error TS2416: Type 'String' is not assignable to type 'string'.
!!! error TS2416: 'string' is a primitive, but 'String' is a wrapper object. Prefer using 'string' when possible.
~
!!! error TS2610: Property 'x' will overwrite the base property in 'Base<string>'. Add a 'declare' modifier or an initializer to avoid this.
}

class Base2 {
Expand All @@ -28,4 +32,6 @@ tests/cases/conformance/types/typeRelationships/apparentType/apparentTypeSubtypi
// is U extends String (S) a subtype of String (T)? Apparent type of U is String so it succeeds
class Derived2<U extends String> extends Base2 { // error because of the prototype's not matching, not because of the instance side
x: U;
~
!!! error TS2610: Property 'x' will overwrite the base property in 'Base2'. Add a 'declare' modifier or an initializer to avoid this.
}
5 changes: 4 additions & 1 deletion tests/baselines/reference/apparentTypeSupertype.errors.txt
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,10 @@ tests/cases/conformance/types/typeRelationships/apparentType/apparentTypeSuperty
Type 'U' is not assignable to type 'string'.
Type 'String' is not assignable to type 'string'.
'string' is a primitive, but 'String' is a wrapper object. Prefer using 'string' when possible.
tests/cases/conformance/types/typeRelationships/apparentType/apparentTypeSupertype.ts(10,5): error TS2610: Property 'x' will overwrite the base property in 'Base'. Add a 'declare' modifier or an initializer to avoid this.


==== tests/cases/conformance/types/typeRelationships/apparentType/apparentTypeSupertype.ts (1 errors) ====
==== tests/cases/conformance/types/typeRelationships/apparentType/apparentTypeSupertype.ts (2 errors) ====
// subtype checks use the apparent type of the target type
// S is a subtype of a type T, and T is a supertype of S, if one of the following is true, where S' denotes the apparent type (section 3.8.1) of S:

Expand All @@ -20,4 +21,6 @@ tests/cases/conformance/types/typeRelationships/apparentType/apparentTypeSuperty
!!! error TS2416: Type 'U' is not assignable to type 'string'.
!!! error TS2416: Type 'String' is not assignable to type 'string'.
!!! error TS2416: 'string' is a primitive, but 'String' is a wrapper object. Prefer using 'string' when possible.
~
!!! error TS2610: Property 'x' will overwrite the base property in 'Base'. Add a 'declare' modifier or an initializer to avoid this.
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ tests/cases/compiler/baseClassImprovedMismatchErrors.ts(8,5): error TS2416: Prop
Types of property 'n' are incompatible.
Type 'string | Derived' is not assignable to type 'string | Base'.
Type 'Derived' is not assignable to type 'string | Base'.
tests/cases/compiler/baseClassImprovedMismatchErrors.ts(8,5): error TS2610: Property 'n' will overwrite the base property in 'Base'. Add a 'declare' modifier or an initializer to avoid this.
tests/cases/compiler/baseClassImprovedMismatchErrors.ts(9,5): error TS2416: Property 'fn' in type 'Derived' is not assignable to the same property in base type 'Base'.
Type '() => string | number' is not assignable to type '() => number'.
Type 'string | number' is not assignable to type 'number'.
Expand All @@ -22,7 +23,7 @@ tests/cases/compiler/baseClassImprovedMismatchErrors.ts(15,5): error TS2416: Pro
Type 'string' is not assignable to type 'number'.


==== tests/cases/compiler/baseClassImprovedMismatchErrors.ts (4 errors) ====
==== tests/cases/compiler/baseClassImprovedMismatchErrors.ts (5 errors) ====
class Base {
n: Base | string;
fn() {
Expand All @@ -39,6 +40,8 @@ tests/cases/compiler/baseClassImprovedMismatchErrors.ts(15,5): error TS2416: Pro
!!! error TS2416: Types of property 'n' are incompatible.
!!! error TS2416: Type 'string | Derived' is not assignable to type 'string | Base'.
!!! error TS2416: Type 'Derived' is not assignable to type 'string | Base'.
~
!!! error TS2610: Property 'n' will overwrite the base property in 'Base'. Add a 'declare' modifier or an initializer to avoid this.
fn() {
~~
!!! error TS2416: Property 'fn' in type 'Derived' is not assignable to the same property in base type 'Base'.
Expand Down
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
tests/cases/compiler/classExpressionPropertyModifiers.ts(2,5): error TS1031: 'declare' modifier cannot appear on a class element.
tests/cases/compiler/classExpressionPropertyModifiers.ts(2,36): error TS1039: Initializers are not allowed in ambient contexts.
tests/cases/compiler/classExpressionPropertyModifiers.ts(3,5): error TS1031: 'export' modifier cannot appear on a class element.


==== tests/cases/compiler/classExpressionPropertyModifiers.ts (2 errors) ====
const a = class Cat {
declare [Symbol.toStringTag] = "uh";
~~~~~~~
!!! error TS1031: 'declare' modifier cannot appear on a class element.
~~~~
!!! error TS1039: Initializers are not allowed in ambient contexts.
export foo = 1;
~~~~~~
!!! error TS1031: 'export' modifier cannot appear on a class element.
Expand Down
Original file line number Diff line number Diff line change
@@ -1,15 +1,19 @@
tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classIsSubtypeOfBaseType.ts(6,5): error TS2610: Property 'foo' will overwrite the base property in 'Base<{ bar: string; }>'. Add a 'declare' modifier or an initializer to avoid this.
tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classIsSubtypeOfBaseType.ts(12,5): error TS2416: Property 'foo' in type 'Derived2' is not assignable to the same property in base type 'Base<{ bar: string; }>'.
Type '{ bar?: string; }' is not assignable to type '{ bar: string; }'.
Property 'bar' is optional in type '{ bar?: string; }' but required in type '{ bar: string; }'.
tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classIsSubtypeOfBaseType.ts(12,5): error TS2610: Property 'foo' will overwrite the base property in 'Base<{ bar: string; }>'. Add a 'declare' modifier or an initializer to avoid this.


==== tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classIsSubtypeOfBaseType.ts (1 errors) ====
==== tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classIsSubtypeOfBaseType.ts (3 errors) ====
class Base<T> {
foo: T;
}

class Derived extends Base<{ bar: string; }> {
foo: {
~~~
!!! error TS2610: Property 'foo' will overwrite the base property in 'Base<{ bar: string; }>'. Add a 'declare' modifier or an initializer to avoid this.
bar: string; baz: number; // ok
}
}
Expand All @@ -20,6 +24,8 @@ tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/cla
!!! error TS2416: Property 'foo' in type 'Derived2' is not assignable to the same property in base type 'Base<{ bar: string; }>'.
!!! error TS2416: Type '{ bar?: string; }' is not assignable to type '{ bar: string; }'.
!!! error TS2416: Property 'bar' is optional in type '{ bar?: string; }' but required in type '{ bar: string; }'.
~~~
!!! error TS2610: Property 'foo' will overwrite the base property in 'Base<{ bar: string; }>'. Add a 'declare' modifier or an initializer to avoid this.
bar?: string; // error
}
}
Loading