typescript: question mark vs type union with undefined

Viewed 1276

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?

1 Answers

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.

Related