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?
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 .
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.
We can use typeof or '==' or '===' to check if a variable is null or undefined in typescript.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With