3

When I assign a partial value to a variable that is declared with a partial type, its type remains partial:

let x: { a: string, b?: string }
x = { a: "a" }
x.b  // fine, x <=> {a:string, b?:string}

The same with a class property:

class X {
  prop: { a: string, b?: string } = { a: "a" }
}
(new X).prop.b // fine, prop <=> {a:string, b?:string}

However, an inherited property doesn't seem to follow this rule and assigns the exact type instead:

class Y extends X {
  prop = { a: "a" }
}
(new Y).prop.b // FAIL, prop <=> {a:string}

PG

How can this behaviour be explained?

georg
  • 211,518
  • 52
  • 313
  • 390
  • It's [this](https://github.com/microsoft/TypeScript/issues/1373), I think. `class C extends E` or `class C implements I` only *checks* that it matches `E` and `I`; it doesn't contextually type the class. – jcalz Oct 11 '19 at 18:08
  • @jcalz: thanks, this appears to be the case – georg Oct 11 '19 at 21:21

1 Answers1

1

The problem is that class Y is created, it will check that prop is compatible with type { a: string, b?: string } but it will then return the exact type of the object literal you passed on. which does not contain b. You can return { a: string, b?: string } directly but then you loose the property names of the object literal, which would be unfortunate. so you can try:

((new Y).prop as { a: string, b?: string }).b
Fateme Fazli
  • 11,582
  • 2
  • 31
  • 48