I've seen code snippets like these:
export interface IUser {
email?: string;
firstName?: string;
lastName?: string;
}
But why are the variable names suffixed by a question mark? This snippet is part of an example of using mongodb with Typescript.
The answer is probably somewhere out there but I seem to be using the wrong keywords since I can't find it.
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.
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 after the variable is called Optional chaining (?.) in JavaScript. The optional chaining operator provides a way to simplify accessing values through connected objects when it's possible that a reference or function may be undefined or null.
In some code snippets, you may have seen that Angular expressions have a question mark after them. Angular refers to it as 'Safe Navigation Operator'. It makes sure that we are not seeing null and undefined values in our application when we want to access properties of an object.
In TypeScript, <name>?: <typename>
a shorthand for <name>: <typename> | undefined
.
This indicates to the type system that a symbol may contain a value of the indicated type or it may contain the value undefined
(which is like null
).
This is important when the (new in TypeScript 2) --strictNullChecks
option is enabled. The documentation on Null- and undefined-aware types option is probably where you should start to understand why this is useful.
It means they can be there but dont have to be. It allows for optional field names. It can be quite common to use.
An example use is allowing users on a website to have an optional display name.
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