Skip to content

public constructor sugar allows promoting field type to optional in subclass #8795

Closed
@rkirov

Description

@rkirov

TypeScript Version:
nightly (1.9.0-dev.20160217)

Code

export class A {
  s: string;
}

export class B extends A {
  constructor(public s?: string) {
    super();
  }
}

Expected behavior:
My understanding is that constructor(public s?: string) is interpreted to mean the field is optional, i.e. desugars to:

  s?: string;
  constructor(s?: string) {
    this.s = s;
  }

Since subclasses can only override fields with subtypes and string | undefined is a supertype of string, this should be an error.

Actual behavior:
The code is accepted. Moreover the produced d.ts file is the following:

declare class A {
    s: string;
}
declare class B extends A {
    s?: string;
    constructor(s?: string);
}

which itself is rejected in further compilations with t.d.ts(4,15): error TS2415: Class 'B' incorrectly extends base class 'A'.

Metadata

Metadata

Assignees

Labels

BugA bug in TypeScriptFixedA PR has been merged for this issue

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions