Class property is not widened to the inherited type

Viewed 43

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?

1 Answers

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
Related