10

When specifying a member with a question mark at the end of it's name, the type signature automatically gets extended to include undefined. It's okay to create an instance without this member:

interface Option{
    val? : number; // hover over val and it tells you that the type is number|undefined
}

let o: Option = {};

The inferred type of val is number|undefined. So far I thought that this was the only effect of the question mark. But manually annotating the type union does not have the same effect:

interface Union{
    val : number|undefined;
}

let u: Union = {}; // compiler complains about missing member val

Why is the second code sample incorrect?

lhk
  • 27,458
  • 30
  • 122
  • 201

1 Answers1

11

Your first option says "val is an optional property with type number". It CAN be there, but it doesn't have to.

Your second options says "val is REQUIRED property, which can have a value of either number or undefined". Hence, it will throw compiler error.

TotallyNewb
  • 3,884
  • 1
  • 11
  • 16
  • His example is with an interface. But what about a class? Isn't optional and required the same in the end? I mean if you access a class with a property you still get undefined whether you declare it as required and possible undefined or optional. So no real difference there? – aProgger Nov 20 '21 at 12:40