microsoft / microsoft/TypeScript
No narrowing on assignment to `this.` union property
Nobody has claimed this yet.
- 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
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- 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