Skip to content

No narrowing on assignment to this. union property #28763

Description

@adzhiljano

TypeScript Version: 3.3.0-dev.20181130

type inference
type inference inheritance
type inference inheritance optional
type inference inheritance optional property
type inference inheritance optional union type
type inference inheritance optional property union type

Code

export class ModelBase {
  modelBaseProp: boolean;

  constructor() {
  }
}

export class Model1 extends ModelBase {
  model1Prop?: number;

  constructor() {
    super();
  }
}

export class Model2 extends ModelBase {
  model2Prop?: string;

  constructor() {
    super();
  }
}

export class Test {
  test: Model1 | Model2;
  constructor() {
    this.test = new Model1();
    this.test.model1Prop = 1;

    this.test = new Model2();
    this.test.model2Prop = 'test';
  }
}

Expected behavior:
No compilation errors.

Actual behavior:
error TS2339: Property 'model1Prop' does not exist on type 'Model1 | Model2'. Property 'model1Prop' does not exist on type 'Model2'
and
error TS2339: Property 'model2Prop' does not exist on type 'Model1 | Model2'. Property 'model2Prop' does not exist on type 'Model1'.

Playground Link: link

Additional info Making the properties in the derived classes non-optional works as expected. Note that the following is working properly: Playground link

export class Model1 {
  model1Prop?: number;

  constructor() {
  }
}

export class Model2 {
  model2Prop?: string;

  constructor() {
  }
}

export class Test {
  test: Model1 | Model2;
  constructor() {
    this.test = new Model1();
    this.test.model1Prop = 1;

    this.test = new Model2();
    this.test.model2Prop = 'test';
  }
}

Activity

  1. RyanCavanaugh commented on Mar 13, 2019

    @RyanCavanaugh
    Member

    Predates 2.0

  2. changed the title [-]Type inference when combining inheritance, optional properties and union type[/-] [+]No narrowing on assignment to `this.` union property[/+] on Oct 30, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    BugA bug in TypeScriptDomain: check: Control FlowThe issue relates to control flow analysis

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions