Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Question mark Typescript variable

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.

like image 926
Arjan Avatar asked Dec 21 '17 11:12

Arjan


People also ask

What is question mark after variable 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.

What is ?: 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 question mark after variable?

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.

What is the question mark used for in Angular?

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.


2 Answers

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.

like image 98
Burt_Harris Avatar answered Sep 20 '22 03:09

Burt_Harris


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.

like image 21
mast3rd3mon Avatar answered Sep 19 '22 03:09

mast3rd3mon