Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

typescript: question mark vs type union with undefined

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?

like image 282
lhk Avatar asked Jun 10 '20 11:06

lhk


People also ask

What does ?: Mean in typescript?

What does ?: mean in TypeScript? Using a question mark followed by a colon ( ?: ) means a property is optional. That said, a property can either have a value based on the type defined or its value can be undefined .

What does a question mark do in typescript?

The question mark ? in typescript is used in two ways: To mention that a particular variable is optional. To pre-check if a member variable is present for an object.

How do you know if a value is undefined in typescript?

We can use typeof or '==' or '===' to check if a variable is null or undefined in typescript.


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.

like image 159
TotallyNewb Avatar answered Oct 11 '22 17:10

TotallyNewb