microsoft / microsoft/TypeScript

No narrowing on assignment to `this.` union property

Open
#28,763 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Bug Domain: check: Control Flow
Dominant language
Go
Stars
111k
Forks
14.3k
Avg merge
2d 4h
Merged PRs (30d)
132

Description

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';
  }
}

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by running the supplied TypeScript 3.3.0-dev reproduction and compare the behavior with the non-inherited example in the issue. Trace the type-checking path for assignments to a property whose type is a union of derived classes, then add a regression test covering the shown code. Done means both assignments compile without errors while unrelated union-property checks remain correct.

Written by the indexing model from the issue text.

Assessment

Tech stack
typescript
Domain
compilers
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
38/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.