How to Deal with Optional Things and “Undefined” in TypeScript

Build an NPM Package in TypeScript from the Ground Up

Article summary

  • What's undefined?

You must tell TypeScript if a property is optional.

  • It's optional. Now what?

Functions and methods can have optional arguments.

Return values when something is missing., make life easier with optional chaining., asserting presence.

  • Dealing with optionality isn't optional.

Working with JavaScript means working with undefined . It’s a standard way to say, “This thing you asked for doesn’t exist.”

Thinking about it all the time tends to break brains, though — and not thinking about it introduces bugs. Thankfully, TypeScript is a great tool for helping you deal with it and writing better code in the process.

What’s undefined?

A project set up with TypeScript’s strict flag will check for all kinds of potential issues in your code. I recommend letting TypeScript be as strict as you can.

undefined typically shows up in a handful of key places:

  • An uninitialized or absent property of an object
  • A potentially-omitted optional argument to a function
  • A return value to indicate something that was requested is missing
  • A potentially-uninitialized variable

TypeScript has tools to deal with all of these.

I don’t think you can program JavaScript without having seen undefined is not a function at least once in your life — and once seems far too small a number.

When you have a JavaScript object and you ask for a property that doesn’t exist, JavaScript will return undefined rather than throwing an error.

In strict mode, this means a couple of things. First, if you don’t tell TypeScript that a property is optional, it will expect it to be set.

Adding ? to the property name on a type, interface, or class definition will mark that property as optional.

c ’s case is interesting. If you hover over Foo in an IDE, you’ll see TypeScript has actually defined bar as number | undefined now.

Even though a and c are different objects, the result of asking for a.bar and c.bar is the same: undefined .

It’s optional. Now what?

Of course, when you have an optional property, TypeScript forces you to deal with it.

You can deal with it in several ways, but the best way is the same way you’d deal with it in JavaScript: by checking to see if what you got is what you expected.

TypeScript understands a number of these kinds of checks and can use them to narrow the picture of what types can possibly make it through to a specific bit of code.

We can use a typeof check against the bar property to see if it is undefined .

This not only supports our a object from above, which has no bar property, but also the c object, which supports the undefined protocol for indicating bar is, well, undefined.

TypeScript will also look at this code and, when inside the if clause, will have narrowed the type of the bar property to number .

TypeScript will also let you “get away” with a truthiness check, like this:

Beware, though: this code has a sneaky bug. 0 is falsy. It will throw if you pass it { bar: 0 } .

Functions and methods can have optional arguments, just as types, interfaces, and classes can have optional properties. Those are also marked with ? :

We actually don’t have much to cover here on how to handle b in this case. Because it will be undefined if not supplied by the caller, it has the type number | undefined just like our optional properties did, and so we can use the same kind of type guard to handle it.

I’ve just changed the flow a little bit to illustrate that TypeScript’s flow-control analysis is pretty flexible:

undefined can also come back from a number of core language calls. Strict TypeScript spots the potential bug here:

The problem is that person is actually not typed string but string | undefined . That’s because Array.prototype.find will return undefined if something’s not found.

Once you have the possibility of undefined , you know how to handle it. See above.

There are some neat features in modern TypeScript (and modern JavaScript, too) that can make your life even easier. For example, say you have a slightly more complicated type, like this:

When things were less deeply-nested, we could do a single typeof check. But look at this expression:

It’s guaranteed to be either a number or undefined . It’ll be the latter if any of bar , baz , or qux or missing or undefined themselves, or the number value of qux if it reaches the end of the expression with all properties present.

This is called optional chaining , and it works by stopping evaluation when it reaches either undefined or null .

This example is a bit contrived, to be sure. But, particularly in JavaScript frameworks where property accesses on things that are possibly not yet initialized are common, or for writing lambda expressions that would otherwise become thick with type guards, ?. is a godsend for simplifying code.

When it comes to classes, TypeScript’s analysis can flag properties that aren’t definitively initialized, and this can save you some pain. It can also cause some pain if the framework you’re using is guaranteed to set those properties before your code will run.

While you can set these properties as optional with ? to make the compiler happy, you’ll make yourself unhappy with all the type guards you’ll then have to write.

If you’re sure that these items will be initialized, you can instead use ! to assert that this property will be set, and TypeScript will assume you know what you’re talking about.

Dealing with optionality isn’t optional.

You have no choice but to deal with optionality and undefined in JavaScript, but the great news is that there are a lot of tools available with which to deal with them. TypeScript has helped make my JavaScript code so much more robust than it had ever been before, and the continued development of the language has been making everything even better all the time.

Related Posts

Module augmentation is a hidden gem in typescript, build a lightweight code generator with typescript and json imports, typescript switches on multiple inputs, keep up with our latest posts..

We’ll send our latest tips, learnings, and case studies from the Atomic braintrust on a monthly basis.

Tell Us About Your Project

We’d love to talk with you about your next great software project. Fill out this form and we’ll get back to you within two business days.

Marius Schulz

Nullish Coalescing: The ?? Operator in TypeScript

TypeScript 3.7 added support for the ?? operator, which is known as the nullish coalescing operator . We can use this operator to provide a fallback value for a value that might be null or undefined .

# Truthy and Falsy Values in JavaScript

Before we dive into the ?? operator, let's recall that JavaScript values can either be truthy or falsy : when coerced to a Boolean, a value can either produce the value true or false . In JavaScript, the following values are considered to be falsy:

All other JavaScript values will produce the value true when coerced to a Boolean and are thus considered truthy.

# Providing Fallback Values with the ?? Operator

The ?? operator can be used to provide a fallback value in case another value is null or undefined . It takes two operands and is written like this:

If the left operand is null or undefined , the ?? expression evaluates to the right operand:

Otherwise, the ?? expression evaluates to the left operand:

Notice that all left operands above are falsy values. If we had used the || operator instead of the ?? operator, all of these expressions would've evaluated to their respective right operands:

This behavior is why you shouldn't use the || operator to provide a fallback value for a nullable value. For falsy values, the result might not be the one you wanted or expected. Consider this example:

The expression options.prettyPrint ?? true lets us provide the default value true in case that the prettyPrint property contains the value null or undefined . If prettyPrint contains the value false , the expression false ?? true still evaluates to false , which is exactly the behavior we want here.

Note that using the || operator here would lead to incorrect results. options.prettyPrint || true would evaluate to true for the values null and undefined , but also for the value false . This would clearly not be intended. I've seen this happen in practice a handful of times, so make sure to keep this case in mind and use towards the ?? operator instead.

# Compiled Output: ES2020 and Newer

The nullish coalescing operator has reached Stage 4 ("Finished") of the TC39 process and is now officially part of ES2020 . Therefore, the TypeScript compiler will emit the ?? operator as is without any downleveling when you're targeting "ES2020" (or a newer language version) or "ESNext" in your tsconfig.json file:

So, this simple expression will be emitted unchanged:

If you're planning on using the ?? operator while targeting "ES2020" or a newer language version, head over to caniuse.com and node.green and make sure that all the JavaScript engines you need to support have implemented the operator.

# Compiled JavaScript Output: ES2019 and Older

If you're targeting "ES2019" or an older language version in your tsconfig.json file, the TypeScript compiler will rewrite the nullish coalescing operator into a conditional expression. That way, we can start using the ?? operator in our code today and still have the compiled code successfully parse and execute in older JavaScript engines.

Let's look at the same simple ?? expression again:

Assuming we're targeting "ES2019" or a lower language version, the TypeScript compiler will emit the following JavaScript code:

The value variable is compared against both null and undefined (the result of the expression void 0 ). If both comparisons produce the value false , the entire expression evaluates to value ; otherwise, it evaluates to fallbackValue .

Now, let's look at a slightly more complex example. Instead of a simple value variable, we're going to use a getValue() call expression as the left operand of the ?? operator:

In this case, the compiler will emit the following JavaScript code (modulo whitespace differences):

You can see that the compiler generated an intermediate variable _a to store the return value of the getValue() call. The _a variable is then compared against null and void 0 and (potentially) used as the resulting value of the entire expression. This intermediate variable is necessary so that the getValue function is only called once.

# Compiled Output: Checking for null and undefined

You might be wondering why the compiler emits the following expression to check the value variable against null and undefined :

Couldn't the compiler emit the following shorter check instead?

Unfortunately, it can't do that without sacrificing correctness. For almost all values in JavaScript, the comparison value == null is equivalent to value === null || value === undefined . For those values, the negation value != null is equivalent to value !== null && value !== undefined . However, there is one value for which these two checks aren't equivalent, and that value is document.all :

The value document.all is not considered to be strictly equal to either null or undefined , but it is considered to be loosely equal to both null and undefined . Because of this anomaly, the TypeScript compiler can't emit value != null as a check because it would produce incorrect results for document.all .

You can read more about this curious behavior in an answer to the Why is document.all falsy? question on Stack Overflow. Oh, the things we do for web compatibility.

This article and 44 others are part of the TypeScript Evolution series. Have a look!

Checking for null and undefined is a common task in TypeScript (and JavaScript in general), and there are several ways to do it. In this article, we’ll explore some of the most common techniques for checking null and undefined values in TypeScript.

The most straightforward way of checking is of course the equality operator

You might notice I’ve used “===” here, which is the strict equality operator. The difference here is that “===” as a stricter operator, will specifically check for null or undefined.

Let’s take a look at this function, which uses the regular equality operator “==” instead of the stricter variant:

With regular equality “==”, here’s what we get:

typescript undefined assignment

The normal, loose equality operator specifically handles this case. If one of the values on either side is null or undefined, if the other one is null or undefined, then they’re equal.

In a lot of scenarios this might not matter, you might just be checking if a variable has a truthy value. In that case you can safely use the regular equality operator. You can also shorten your code, to something like:

But there is a difference between null and undefined, and you might want to handle that separately in some cases. Null often means something is specifically meant to have no value, whereas undefined tends to mean something hasn’t been given a value yet.

An example might be something like if you’re using a function to fetch some data . Null might mean the search has been completed, but the data wasn’t found, whereas undefined might indicate that the fetch was never completed successfully.

Coalescing Operator

Another way to check for null or undefined is to use the nullish coalescing operator (??), which was introduced in TypeScript 3.7. This operator returns the left-hand side of the expression if it’s not null or undefined, and the right-hand side otherwise:

Here’s what we get outputted:

typescript undefined assignment

The most common use case for this is for default values, something like:

You might see this a lot for things like environment variables:

I.e. if we get API_URL as an environment variable, use that value, but otherwise default to the value on the right.

As well as the null coalescing operator, you might also find the less commonly used Nullish coalescing assignment operator:

In the example above, var1 starts off as null. The next assignment does store the string in var1, since var1 is null. Then since we have ‘Replacing null’ in var1 now, the next assignment gets skipped.

This can be used to assign a value only if the variable is null. It’s less commonly seen, but you might still run into it.

Optional Chaining

Another shortcut TypeScript provides for checking for null or undefined is optional chaining. It’s used for accessing properties of an object that might be undefined or null.

Let’s take this type:

We get an error with this code, since unfortunately, our user might not exist.

So we could use one of the approaches we’ve learnt before, and check beforehand:

But with optional chaining, we can shorten this to:

And as you can work out from the name, we can chain this as much as we need to:

As soon as one part fails, the chain won’t continue.

Thanks for reading! Checking for null and undefined values is an important task in TypeScript. By using the techniques we’ve gone over, you can ensure that your code behaves as expected even when dealing with null and undefined values.

Remember to choose the technique that fits your code best, bearing in mind whether or not you need your code to discern between “null” and “undefined”. If you’re interested in further reading, why not delve further into the rest of TypeScript’s primitive types .

If you liked this article, feel free to leave a comment below!

Related Posts:

  • event.target.name is undefined: What you need to know
  • How Do I Create React App And Open It In VS Code?
  • How To Start a New NextJS Project and Open It in VS Code?
  • How To Create a Svelte App And Open It In VS Code?
  • How To Clean Up Your TypeScript Code With Optional Chaining
  • Map Your Way to Cleaner Code With The Map Function…

Avatar photo

👋 Hey, I'm Omari Thompson-Edwards

💬 leave a comment cancel reply.

Your email address will not be published. Required fields are marked *

Upmostly brings you original JavaScript framework tutorials every week.

  • Cheatsheets
  • Write For Us

Copyright © 2024 Upmostly

Advisory boards aren’t only for executives. Join the LogRocket Content Advisory Board today →

LogRocket blog logo

  • Product Management
  • Solve User-Reported Issues
  • Find Issues Faster
  • Optimize Conversion and Adoption
  • Start Monitoring for Free

How to dynamically assign properties to an object in TypeScript

typescript undefined assignment

Editor’s note: This article was updated on 6 October 2023, introducing solutions like type assertions and the Partial utility type to address the TypeScript error highlighted.

How To Dynamically Assign Properties To An Object In TypeScript

JavaScript is a dynamically typed language, meaning that a variable’s type is determined at runtime and by what it holds at the time of execution. This makes it flexible but also unreliable and prone to errors because a variable’s value might be unexpected.

TypeScript, on the other hand, is a statically typed version of JavaScript — unlike JavaScript, where a variable can change types randomly, TypeScript defines the type of a variable at its declaration or initialization.

Dynamic property assignment is the ability to add properties to an object only when they are needed. This can occur when an object has certain properties set in different parts of our code that are often conditional.

In this article, we will explore some ways to enjoy the dynamic benefits of JavaScript alongside the security of TypeScript’s typing in dynamic property assignment.

Consider the following example of TypeScript code:

This seemingly harmless piece of code throws a TypeScript error when dynamically assigning name to the organization object:

An Error Is Thrown When Dynamically Assigning A Property To An Object

See this example in the TypeScript Playground .

The source of confusion, perhaps rightly justified if you’re a TypeScript beginner, is: how could something that seems so simple be such a problem in TypeScript?

The TL;DR of it all is that if you can’t define the variable type at declaration time, you can use the Record utility type or an object index signature to solve this. But in this article, we’ll go through the problem itself and work toward a solution that should work in most cases.

The problem with dynamically assigning properties to objects

Generally speaking, TypeScript determines the type of a variable when it is declared. This determined type stays the same throughout your application. There are exceptions to this rule, such as when considering type narrowing or working with the any type, but otherwise, this is a general rule to remember.

In the earlier example, the organization object is declared as follows:

There is no explicit type assigned to this variable, so TypeScript infers a type of organization based on the declaration to be {} , i.e., the literal empty object.

If you add a type alias, you can explore the type of organization :

Exploring The Literal Object Type

See this in the TypeScript Playground .

When you then try to reference the name prop on this empty object literal:

You receive the following error:

There are many ways to solve the TypeScript error here. Let’s consider the following:

Solution 1: Explicitly type the object at declaration time

This is the easiest solution to reason through. At the time you declare the object, go ahead and type it, and assign all the relevant values:

This eliminates any surprises. You’re clearly stating what this object type is and rightly declaring all relevant properties when you create the object.

However, this is not always feasible if the object properties must be added dynamically, which is why we’re here.

Solution 2: Use an object index signature

Occasionally, the properties of the object truly need to be added at a time after they’ve been declared. In this case, you can use the object index signature, as follows:

When the organization variable is declared, you can explicitly type it to the following: {[key: string] : string} .

You might be used to object types having fixed property types:

However, you can also substitute name for a “variable type.” For example, if you want to define any string property on obj :

Note that the syntax is similar to how you’d use a variable object property in standard JavaScript:

The TypeScript equivalent is called an object index signature.

typescript undefined assignment

Over 200k developers use LogRocket to create better digital experiences

typescript undefined assignment

Moreover, note that you could type key with other primitives:

Solution 3: Use the Record Utility Type

The Record utility type allows you to constrict an object type whose properties are Keys and property values are Type . It has the following signature: Record<Keys, Type> .

In our example, Keys represents string and Type . The solution here is shown below:

Instead of using a type alias, you can also inline the type:

Using The Record Utility Type

Solution 4: Use the Map data type

A Map object is a fundamentally different data structure from an object , but for completeness, you could eliminate this problem if you were using Map .

Consider the starting example rewritten to use a Map object:

With Map objects, you’ll have no errors when dynamically assigning properties to the object:

Dark Background Typescript Playground Showing Map Object No Errors

This seems like a great solution at first, but the caveat is your Map object is weakly typed. You can access a nonexisting property and get no warnings at all:

See the TypeScript Playground .

This is unlike the standard object. By default, the initialized Map has the key and value types as any — i.e., new () => Map<any, any> . Consequently, the return type of the s variable will be any :

Dark Background Typescript Playground Showing Constant S With Type Any Indicated By Red Arrow

When using Map , at the very least, I strongly suggest passing some type information upon creation. For example:

s will still be undefined, but you won’t be surprised by its code usage. You’ll now receive the appropriate type for it:

Dark Background Typescript Playground Showing Properly Typed Map Value With Const S With Type String Undefined Indicated By Red Arrow

If you truly don’t know what the keys of the Map will be, you can go ahead and represent this at the type level:

And if you’re not sure what the keys or values are, be safe by representing this at the type level:

Solution 5: Consider an optional object property

This solution won’t always be possible, but if you know the name of the property to be dynamically assigned, you can optionally provide this when initializing the object as shown below:

If you don’t like the idea of using optional properties, you can be more explicit with your typing as shown below:

Solution 6: Leveraging type assertions

TypeScript type assertion is a mechanism that tells the compiler the variable’s type and overrides what it infers from the declaration or assignment. With this, we are telling the compiler to trust our understanding of the type because there will be no type verification.

We can perform a type assertion by either using the <> brackets or the as keyword. This is particularly helpful with the dynamic property assignment because it allows the properties we want for our object to be dynamically set because TypeScript won’t enforce them.

Let’s take a look at applying type assertions to our problem case:

Dark Background Typescript Playground Showing Dynamic Property Assignment Using Type Assertion

Note that with type assertions, the compiler is trusting that we will enforce the type we have asserted. This means if we don’t, for example, set a value for organization.name , it will throw an error at runtime that we will have to handle ourselves.

Solution 7: Use the Partial utility type

TypeScript provides several utility types that can be used to manipulate types. Some of these utility types are Partial , Omit , Required , and Pick .

For dynamic property assignments, we will focus specifically on the Partial utility type. This takes a defined type and makes all its properties optional. Thus, we can initialize our object with any combination of its properties, from none to all, as each one is optional:

In our example with the Partial utility type, we defined our organization object as the type partial Org , which means we can choose not to set a phoneNumber property:

Dark Background Typescript Playground Showing Dynamic Property Assignment Using Utility Type Partial

Grouping and comparing the options for adding properties in TypeScript

In this article, we explored the different options for setting properties dynamically in TypeScript. These options can be grouped together by their similarities.

Index/Key signatures

This group of options allows you to define the type of keys allowed without limiting what possible keys can exist. The options in this group include:

  • Using an object index signature
  • Using the Record utility type
  • Using the Map data type (with key/value typing)

With these, we can define that our object will take string indexes and decide what types to support as values, like String , Number , Boolean , or Any :

See in TypeScript Playground .

Pro: The main benefit of these methods is the ability to dynamically add properties to an object while still setting expectations for the potential types of keys and values.

Con: The main disadvantage of this way of defining objects is that you can’t predict what keys our objects will have and so some references may or may not be defined. An additional disadvantage is that if we decide to define our key signature with type Any , then the object becomes even more unpredictable.

Conditional/Optional properties

This set of object assignment methods shares a common feature: the definition of optional properties. This means that the range of possible properties are known but some may or may not be set. The options in this group include:

  • Using optional object properties
  • Using the Partial utility type
  • Using type assertions

See this example in the TypeScript Playground , or in the code block below:

Note: While these options mean that the possible keys are known and may not be set, TypeScript’s compiler won’t validate undefined states when using type assertions. This can lead to unhandled exceptions during runtime. For example, with optional properties and the Partial utility type, name has type string or undefined . Meanwhile, with type assertions, name has type string .

Pro: The advantage of this group of options is that all possible object keys and values are known.

Con: The disadvantage is that while the possible keys are known, we don’t know if those keys have been set and will have to handle the possibility that they are undefined.

Apart from primitives, the most common types you’ll have to deal with are likely object types. In cases where you need to build an object dynamically, take advantage of the Record utility type or use the object index signature to define the allowed properties on the object.

If you’d like to read more on this subject, feel free to check out my cheatsheet on the seven most-asked TypeScript questions on Stack Overflow, or tweet me any questions . Cheers!

LogRocket : Full visibility into your web and mobile apps

LogRocket Dashboard Free Trial Banner

LogRocket is a frontend application monitoring solution that lets you replay problems as if they happened in your own browser. Instead of guessing why errors happen or asking users for screenshots and log dumps, LogRocket lets you replay the session to quickly understand what went wrong. It works perfectly with any app, regardless of framework, and has plugins to log additional context from Redux, Vuex, and @ngrx/store.

In addition to logging Redux actions and state, LogRocket records console logs, JavaScript errors, stacktraces, network requests/responses with headers + bodies, browser metadata, and custom logs. It also instruments the DOM to record the HTML and CSS on the page, recreating pixel-perfect videos of even the most complex single-page and mobile apps.

Try it for free .

Share this:

  • Click to share on Twitter (Opens in new window)
  • Click to share on Reddit (Opens in new window)
  • Click to share on LinkedIn (Opens in new window)
  • Click to share on Facebook (Opens in new window)
  • #typescript

Hey there, want to help make our blog better?

Join LogRocket’s Content Advisory Board. You’ll help inform the type of content we create and get access to exclusive meetups, social accreditation, and swag.

typescript undefined assignment

Stop guessing about your digital experience with LogRocket

Recent posts:.

typescript undefined assignment

Go long by generating PDFs in Golang with Maroto

Go, also known as Golang, is a statically typed, compiled programming language designed by Google. It combines the performance and […]

typescript undefined assignment

MobX adoption guide: Overview, examples, and alternatives

MobX is a lightweight, boilerplate-free state management library that offers a reactive approach to state management.

typescript undefined assignment

Hydration visualization in Angular 18 using debugging tools

Angular 18’s hydration error visualization boosts application debugging by clearly identifying which components are fully hydrated.

typescript undefined assignment

Turbopack adoption guide: Overview, examples, and alternatives

Turbopack is a next-generation incremental bundler optimized for JavaScript and TypeScript. Let’s explore why and how to adopt it.

typescript undefined assignment

3 Replies to "How to dynamically assign properties to an object in TypeScript"

I know this is explicitly for TypeScript, and I think type declarations should always be first. But in general, you can also use a Map object. If it’s really meant to by dynamic, might as well utilize the power of Map.

Great suggestion (updated the article). It’s worth mentioning the weak typing you get by default i.e., with respect to Typescript.

Hi, thanks for your valuable article please consider ‘keyof type’ in TypeScript, and add this useful solution if you are happy have nice time

Leave a Reply Cancel reply

TypeScript tutorial

Typescript exercises, typescript null & undefined.

TypeScript has a powerful system to deal with null or undefined values.

By default null and undefined handling is disabled, and can be enabled by setting strictNullChecks to true.

The rest of this page applies for when strictNullChecks is enabled.

null and undefined are primitive types and can be used like other types, such as string .

When strictNullChecks is enabled, TypeScript requires values to be set unless undefined is explicitly added to the type.

Optional Chaining

Optional Chaining is a JavaScript feature that works well with TypeScript's null handling. It allows accessing properties on an object, that may or may not exist, with a compact syntax. It can be used with the ?. operator when accessing properties.

Nullish Coalescence

Nullish Coalescence is another JavaScript feature that also works well with TypeScript's null handling. It allows writing expressions that have a fallback specifically when dealing with null or undefined . This is useful when other falsy values can occur in the expression but are still valid. It can be used with the ?? operator in an expression, similar to using the && operator.

Get Certified!

Null assertion.

TypeScript's inference system isn't perfect, there are times when it makes sense to ignore a value's possibility of being null or undefined . An easy way to do this is to use casting, but TypeScript also provides the ! operator as a convenient shortcut.

Just like casting, this can be unsafe and should be used with care.

Array bounds handling

Even with strictNullChecks enabled, by default TypeScript will assume array access will never return undefined (unless undefined is part of the array type).

The config noUncheckedIndexedAccess can be used to change this behavior.

Get Certified

COLOR PICKER

colorpicker

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: [email protected]

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail: [email protected]

Top Tutorials

Top references, top examples, get certified.

Object is possibly 'undefined' error in TypeScript [Solved]

avatar

Last updated: Feb 27, 2024 Reading time · 5 min

banner

# Object is possibly 'undefined' error in TypeScript

The "Object is possibly 'undefined'" error occurs when we try to access a property on an object that may be undefined (e.g. marked as optional).

To solve the error, use optional chaining to short-circuit if the reference is equal to null , e.g. p1?.address?.country .

object is possibly undefined

Here is an example of how the error occurs.

ts object is possibly undefined

The address property on the Person type is marked as optional , so it might be undefined .

This is why we aren't able to safely access the country or city properties.

# Using the optional chaining (?.) operator

You can use the optional chaining (?.) operator to resolve the issue.

using optional chaining operator to solve the error

The question mark dot (?.) syntax is called optional chaining in TypeScript.

It is like using dot notation to access a nested property of an object but instead of throwing an error if the reference is nullish ( null or undefined ), it short-circuits returning undefined .

# Providing a fallback value if the property doesn't exist

You can combine the optional chaining (?.) operator with the nullish coalescing (??) operator to specify a default value if the property doesn't exist.

providing fallback value if property does not exist

If the value to the left of the nullish coalescing operator (??) is equal to null or undefined , the value to the right is returned, otherwise, the value to the left of the operator is returned.

If trying to access the nested country property on the object returns undefined , then the value to the right of the nullish coalescing (??) operator is returned.

# Using an if statement to solve the error

An alternative approach is to use a simple if statement as a type guard .

using if statement to solve the error

We used an if statement to check if the p1.address property is not equal to undefined or null .

Notice that we used the loose inequality (!=) operator, which checks for both undefined and null . You can exclusively check for undefined with strict not equals (!==).

The loose comparison covers both undefined and null , because in a loose comparison undefined is equal to null .

# Using the non-null assertion operator to solve the error

If you are sure the property cannot possibly have a null value , you can use the non-null assertion operator.

using non null assertion operator to solve the error

The exclamation mark is the non-null assertion operator in TypeScript.

When you use this approach, you basically tell TypeScript that this value will never be null or undefined .

We used it right after the address property, so we are telling TypeScript that p1.address will never have a value of null or undefined .

# Solve the error using the logical AND (&&) operator

If you are making a comparison in an if statement, use the logical AND (&&) operator to make sure the property is of the correct type.

The logical AND (&&) operator makes sure the address property isn't undefined , that num exists on the object and is a number before comparing it to the number 10 .

This is needed because if the reference is nullish ( null or undefined ), the optional chaining operator (?.) will return undefined and TypeScript doesn't allow us to compare undefined to a number .

For example, this would fail:

The result might have a value of undefined because that's the return value of the optional chaining (?.) operator when it short-circuits.

The num property might have a value of undefined , so we can't directly compare it to a number .

Another common way to avoid getting the error is to use the logical AND (&&) operator.

All the values in the if condition have to be truthy for the if block to run.

The falsy values in JavaScript are: undefined , null , false , 0 , "" (empty string), NaN (not a number).

All other values are truthy.

This is why TypeScript is able to infer the type of the result variable to be string in the if block.

# Using the typeof operator to solve the error

An even better way to get around the error in this situation is to use the typeof operator.

We explicitly check if the type of the country property is a string.

This is better than checking if the value is truthy because empty strings are falsy values in JavaScript (and TypeScript).

Here is an example that illustrates why using the typeof operator is better.

This else block runs in the example above.

It's always better to be explicit and use the typeof operator when possible. It helps us avoid some difficult-to-spot bugs.

# Conclusion

The "Object is possibly 'undefined'" error occurs when we try to access a property on an object that may have a value of undefined .

To solve the error, use the optional chaining operator or a type guard to make sure the reference is not undefined before accessing properties.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

  • Object is possibly 'null' error in TypeScript [Solved]
  • Object is of type 'unknown' Error in TypeScript [Solved]
  • Object literal may only specify known properties in TS
  • Type 'unknown' is not assignable to type in TypeScript

book cover

Borislav Hadzhiev

Web Developer

buy me a coffee

Copyright © 2024 Borislav Hadzhiev

TekTutorialsHub-Logo

Null Vs Undefined in TypeScript

TypeScript has two special values for Null and Undefined . Both represent no value or  absence of any value . The difference between  Null  &  Undefined  is subtle and confusing. Prior to TypeScript 2.0 , we could assign them all other types like numbers, strings, etc. Such assignment has been the source of a lot of errors like TypeError s or  ReferenceError s in JavaScript. The StrictNullChecks introduced in version 2.0 raises compile-time errors if we use Null or Undefined . In this tutorial, we compare Null and Undefined . let us learn the similarities and differences etc.

Table of Contents

Undefined & Null

Undefined is the default value for uninitialized variables, setting the value, checking for null & undefined, comparing null with undefined, arithmetic operations.

The value  undefined  means  value is not assigned  &  you don’t know its value . It is an  unintentional absence of value . It means that a variable has been declared but has not yet been assigned a value.

The value  null  indicates that  you know  that the field  does not have a value . It is an  intentional absence of value .

Whenever we declare a variable without initializing it with a value, TypeScript initializes it as  undefined . But TypeScript never assigns null to any variable. We have to assign Null to variable to make it null.

The following example declares the variable  foo . We have not given it any initial value. By default, it gets the value  undefined . But for null, we need to assign a value to it

foo:any;               .log(foo);         //undefined =null                  //Setting its value to null .log(foo);         //null

The following are some of the instances where a variable gets the value undefined

  • Uninitialized variable
  • Optional function argument that has not been supplied
  • Non-existing object Property
  • Non-existing array elements

Note that in the example above foo is of type any , which means that no type checking . But if we assigned a type like say number , then we will see compiler throwing errors like 'foo' is used before being assigned or Type 'null' is not assignable to type 'number' deepening on whether you have enabled strictNullChecks or not.

foo:number;             .log(foo);         //Variable 'foo' is used before being assigned =null                  //Type 'null' is not assignable to type 'number'. .log(foo);        

The Undefined & null also have corresponding types named after them. The Data Type of undefined is undefined and that of null is null.

We can create a variable of type undefined or null by annotating them with type just like any other  variable declaration

a:undefined       //a is a variable of type undefined b:null=null       //b is a variable of type null .log(typeof(a))   //undefined .log(typeof(b))   //object

But using typeof on a null  variable  shows it as an object. This is a very old  bug  in JavaScript

The only value that you can assign to an undefined variable is undefined.  You can assign null only if StrictNullCheck is disabled). Any other values like string, object, numbers, etc are not allowed.

uVar: undefined; =undefined;     //ok =null;          //Type 'null' is not assignable to type 'undefined' =10;            //type '10' is not assignable to type 'undefined' ={}             //Type '{}' is not assignable to type 'undefined'

The only value that you can assign to it is null.  You can also assign undefined only if StrictNullCheck is disabled.

nVar: null; =null;          //ok =undefined;     //Type 'null' is not assignable to type 'null'. =10;          //type '10' is not assignable to type 'null' ={}           //Type '{}' is not assignable to type 'null'

Both null & undefined is falsy value in TypeScript. i.e. when we use them in a boolean expression they are coerced to false.

let a=undefined let b=null if (!a) console.log('false')        //false if (!b) console.log('false')        //false

But they are neither false nor true.

let a=undefined let b=null if (a==false) console.log('false')       if (a==true) console.log('true')       if (b==false) console.log('false')       if (b==true) console.log('true')  
.log(true && null)   //null .log(true || null)   //true .log(true && undefined)   //undefined .log(true || undefined)   //true

You can use  typeof  operator to check for undefined but not null as it returns “object”. You can use the == & === operator to check their values

nVar:any; .log(nVar)                     //undefined .log(typeof nVar)              //undefined .log(nVar==undefined)          //true   .log(nVar===undefined)         //true

Checking for null.

nVar:any; =null; .log(nVar)                     //null .log(typeof nVar)              //object     //Do not use typeof for null .log(nVar==null)               //true .log(nVar===null)              //true

Comparing null with undefined results in different results depending on whether you use an equality checker ( == ) or strict equality checker ( === )

null and undefined both represents no value hence equality checker ( == ) returns true. This is because the equality checker does not check for data type

.log(null == undefined)      //true

But strict equality checker returns false because it also checks for the data type.

.log(null === undefined)      //false

Converting undefined to Number will result in NaN .

b=undefined .log(Number(b))  //NaN

While null is coerced to 0

b=null .log(Number(b))  //0

Compiler throws an error if we use undefined in arithmetic operations. The error depends on whether the strictNullChecks is enabled or not.

a=10;                //Type of a is number b:any=undefined      //Type of b is undefined   .log(a+b)        //object is possibly 'undefined' .log(a+b)        //Operator '+' cannot be applied to types 'number' and 'undefined'

You can opt out of Type Checking by declaring the variable as any. Then the undefined is coerced to NaN and the result will be NaN.

a=10;                //Type of a is number b:any=undefined      //Type of b is any.  No Type  Check if Performed .log(a+b)        //NaN

Similarly, using null in arithmetic operations results in compiler errors.

a=10               // a is of type number b=null             // b is of Type Null .log(a+b)        //object is possibly 'null' .log(a+b)        //Operator '+' cannot be applied to types 'number' and 'null'.

But if you opt-out of type checking then the null is coerced to 0 .

a=10                // a is of type number b:any=null          // b is of Type Null .log(a+b)        //10

The Typeof Operator returns the data type of the variable. It returns the data type of undefined correctly but returns “object” as the data type of null. This is a well-known  bug  in JavaScript

a:undefined b=null .log(typeof(a))   //undefined .log(typeof(b))   //object
NullUndefined
Null is the intentional absence of a value (null is explicit)Undefined is the unintentional absence of a value (undefined is implicit)
Null must be assigned to a variableThe default value of any unassigned variable is undefined.
The typeof null is an object. (and not type null)Typeof undefined is undefined type
You can empty a variable by setting it to nullYou can Undefine a variable by setting it to Undefined
null is always falsyundefined is always falsy
null is equal to undefined when compared with == (equality check)
null is not equal to undefined when compared with === (strict equality check)
When we convert null to a number it becomes zerowhen we convert undefined to number it becomes NaN
You can represent undefined as a JSON (JavaScript Object Notation)null is a valid value in JSON.
  • Everyday Types
  • TypeScript Tutorial
  • Number Data Type
  • NaN in Typescript
  • Min, Max & Safe Values
  • EPSILON & Floating Point Precision
  • BigInt data type
  • BigInt Vs Number
  • Boolean Data Type
  • StrictNullChecks
  • Null Vs Undefined
  • Object & Object Data Type
  • Unknown Type

Related Posts

What is TypeScript An Introduction

Introduction to Typescript. What is TypeScript

Installing TypeScript

Typescript Installation & environment setup

1 thought on “null vs undefined in typescript”.

There is no example that shows the actual use, when to use null when undefined, show examples not just plain text.

Leave a Comment Cancel Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed .

  • Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
  • Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand
  • OverflowAI GenAI features for Teams
  • OverflowAPI Train & fine-tune LLMs
  • Labs The future of collective knowledge sharing
  • About the company Visit the blog

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Get early access and see previews of new features.

Why does TypeScript give a "possibly undefined" error when using a conditional and `Array.map`? [duplicate]

Consider this minimal example:

On line 3, TS complains that 'a' is possibly undefined . As far as I can see, it must be defined in a single-threaded environment, as the ternary operator eliminates the possibility that it is undefined. (The same occurs if the ternary is replaced with an if/else statement.)

I think that the Array.map callback must be the culprit somehow, because if the third line is instead

then there are no complaints. Is TS possibly worried that the callback in map could assign to a such that it becomes undefined? If so, surely it's not hard for the compiler to see that this cannot happen.

  • conditional-operator

user19642323's user avatar

  • This is ms/TS#9998 . See linked q/a above. –  jcalz Commented 2 days ago
  • 1 @jcalz I see, thanks. This makes a lot of sense. –  user19642323 Commented 2 days ago

Browse other questions tagged typescript callback conditional-operator or ask your own question .

  • The Overflow Blog
  • From PHP to JavaScript to Kubernetes: how one backend engineer evolved over time
  • Featured on Meta
  • We've made changes to our Terms of Service & Privacy Policy - July 2024
  • Bringing clarity to status tag usage on meta sites
  • Feedback requested: How do you use tag hover descriptions for curating and do...
  • What does a new user need in a homepage experience on Stack Overflow?

Hot Network Questions

  • How to justify a ban on exclusivist religions?
  • Why is the passive used in this sentence?
  • Aftermarket stereo wiring help for 2012 chevy colorado WT
  • Has the government of Afghanistan clarified what they mean/intend by the ban on 'images of living beings'?
  • An integral using Mathematica or otherwise
  • Which cards use −5 V and −12 V in IBM PC compatible systems?
  • Op Amp Feedback Resistors
  • Postdoc supervisor has stopped helping
  • How to extract code into library allowing changes without workflow overhead
  • how replicate this effect with geometry nodes
  • Will this be the first time, that there are more People an ISS than seats in docked Spacecraft?
  • When a submarine blows its ballast and rises, where did the energy for the ascent come from?
  • What do the hexadecimal numbers represent on the ls output of the /dev directory?
  • What's the counterpart to "spheroid" for a circle? There's no "circoid"
  • If physics can be reduced to mathematics (and thus to logic), does this mean that (physical) causation is ultimately reducible to implication?
  • Are there any virtues in virtue ethics that cannot be plausibly grounded in more fundamental utilitarian principles?
  • The hat-check problem
  • If the Collatz conjecture is undecidable, then it is true
  • Are chord inversions determined solely by the lowest note, even in a broken chord?
  • Visualizing histogram of data on unit circle?
  • What's the Matter?
  • Millennial reign and New Heaven and New Earth
  • What does 北渐 mean?
  • Idiomatic alternative to “going to Canossa”

typescript undefined assignment

Was this page helpful?

Variable Declaration

let and const are two relatively new concepts for variable declarations in JavaScript. As we mentioned earlier , let is similar to var in some respects, but allows users to avoid some of the common “gotchas” that users run into in JavaScript.

const is an augmentation of let in that it prevents re-assignment to a variable.

With TypeScript being an extension of JavaScript, the language naturally supports let and const . Here we’ll elaborate more on these new declarations and why they’re preferable to var .

If you’ve used JavaScript offhandedly, the next section might be a good way to refresh your memory. If you’re intimately familiar with all the quirks of var declarations in JavaScript, you might find it easier to skip ahead.

var declarations

Declaring a variable in JavaScript has always traditionally been done with the var keyword.

As you might’ve figured out, we just declared a variable named a with the value 10 .

We can also declare a variable inside of a function:

and we can also access those same variables within other functions:

In this above example, g captured the variable a declared in f . At any point that g gets called, the value of a will be tied to the value of a in f . Even if g is called once f is done running, it will be able to access and modify a .

Scoping rules

var declarations have some odd scoping rules for those used to other languages. Take the following example:

Some readers might do a double-take at this example. The variable x was declared within the if block , and yet we were able to access it from outside that block. That’s because var declarations are accessible anywhere within their containing function, module, namespace, or global scope - all which we’ll go over later on - regardless of the containing block. Some people call this var -scoping or function-scoping . Parameters are also function scoped.

These scoping rules can cause several types of mistakes. One problem they exacerbate is the fact that it is not an error to declare the same variable multiple times:

Maybe it was easy to spot out for some experienced JavaScript developers, but the inner for -loop will accidentally overwrite the variable i because i refers to the same function-scoped variable. As experienced developers know by now, similar sorts of bugs slip through code reviews and can be an endless source of frustration.

Variable capturing quirks

Take a quick second to guess what the output of the following snippet is:

For those unfamiliar, setTimeout will try to execute a function after a certain number of milliseconds (though waiting for anything else to stop running).

Ready? Take a look:

Many JavaScript developers are intimately familiar with this behavior, but if you’re surprised, you’re certainly not alone. Most people expect the output to be

Remember what we mentioned earlier about variable capturing? Every function expression we pass to setTimeout actually refers to the same i from the same scope.

Let’s take a minute to consider what that means. setTimeout will run a function after some number of milliseconds, but only after the for loop has stopped executing; By the time the for loop has stopped executing, the value of i is 10 . So each time the given function gets called, it will print out 10 !

A common work around is to use an IIFE - an Immediately Invoked Function Expression - to capture i at each iteration:

This odd-looking pattern is actually pretty common. The i in the parameter list actually shadows the i declared in the for loop, but since we named them the same, we didn’t have to modify the loop body too much.

let declarations

By now you’ve figured out that var has some problems, which is precisely why let statements were introduced. Apart from the keyword used, let statements are written the same way var statements are.

The key difference is not in the syntax, but in the semantics, which we’ll now dive into.

Block-scoping

When a variable is declared using let , it uses what some call lexical-scoping or block-scoping . Unlike variables declared with var whose scopes leak out to their containing function, block-scoped variables are not visible outside of their nearest containing block or for -loop.

Here, we have two local variables a and b . a ’s scope is limited to the body of f while b ’s scope is limited to the containing if statement’s block.

Variables declared in a catch clause also have similar scoping rules.

Another property of block-scoped variables is that they can’t be read or written to before they’re actually declared. While these variables are “present” throughout their scope, all points up until their declaration are part of their temporal dead zone . This is just a sophisticated way of saying you can’t access them before the let statement, and luckily TypeScript will let you know that.

Something to note is that you can still capture a block-scoped variable before it’s declared. The only catch is that it’s illegal to call that function before the declaration. If targeting ES2015, a modern runtime will throw an error; however, right now TypeScript is permissive and won’t report this as an error.

For more information on temporal dead zones, see relevant content on the Mozilla Developer Network .

Re-declarations and Shadowing

With var declarations, we mentioned that it didn’t matter how many times you declared your variables; you just got one.

In the above example, all declarations of x actually refer to the same x , and this is perfectly valid. This often ends up being a source of bugs. Thankfully, let declarations are not as forgiving.

The variables don’t necessarily need to both be block-scoped for TypeScript to tell us that there’s a problem.

That’s not to say that a block-scoped variable can never be declared with a function-scoped variable. The block-scoped variable just needs to be declared within a distinctly different block.

The act of introducing a new name in a more nested scope is called shadowing . It is a bit of a double-edged sword in that it can introduce certain bugs on its own in the event of accidental shadowing, while also preventing certain bugs. For instance, imagine we had written our earlier sumMatrix function using let variables.

This version of the loop will actually perform the summation correctly because the inner loop’s i shadows i from the outer loop.

Shadowing should usually be avoided in the interest of writing clearer code. While there are some scenarios where it may be fitting to take advantage of it, you should use your best judgement.

Block-scoped variable capturing

When we first touched on the idea of variable capturing with var declaration, we briefly went into how variables act once captured. To give a better intuition of this, each time a scope is run, it creates an “environment” of variables. That environment and its captured variables can exist even after everything within its scope has finished executing.

Because we’ve captured city from within its environment, we’re still able to access it despite the fact that the if block finished executing.

Recall that with our earlier setTimeout example, we ended up needing to use an IIFE to capture the state of a variable for every iteration of the for loop. In effect, what we were doing was creating a new variable environment for our captured variables. That was a bit of a pain, but luckily, you’ll never have to do that again in TypeScript.

let declarations have drastically different behavior when declared as part of a loop. Rather than just introducing a new environment to the loop itself, these declarations sort of create a new scope per iteration . Since this is what we were doing anyway with our IIFE, we can change our old setTimeout example to just use a let declaration.

and as expected, this will print out

const declarations

const declarations are another way of declaring variables.

They are like let declarations but, as their name implies, their value cannot be changed once they are bound. In other words, they have the same scoping rules as let , but you can’t re-assign to them.

This should not be confused with the idea that the values they refer to are immutable .

Unless you take specific measures to avoid it, the internal state of a const variable is still modifiable. Fortunately, TypeScript allows you to specify that members of an object are readonly . The chapter on Interfaces has the details.

let vs. const

Given that we have two types of declarations with similar scoping semantics, it’s natural to find ourselves asking which one to use. Like most broad questions, the answer is: it depends.

Applying the principle of least privilege , all declarations other than those you plan to modify should use const . The rationale is that if a variable didn’t need to get written to, others working on the same codebase shouldn’t automatically be able to write to the object, and will need to consider whether they really need to reassign to the variable. Using const also makes code more predictable when reasoning about flow of data.

Use your best judgement, and if applicable, consult the matter with the rest of your team.

The majority of this handbook uses let declarations.

Destructuring

Another ECMAScript 2015 feature that TypeScript has is destructuring. For a complete reference, see the article on the Mozilla Developer Network . In this section, we’ll give a short overview.

Array destructuring

The simplest form of destructuring is array destructuring assignment:

This creates two new variables named first and second . This is equivalent to using indexing, but is much more convenient:

Destructuring works with already-declared variables as well:

And with parameters to a function:

You can create a variable for the remaining items in a list using the syntax ... :

Of course, since this is JavaScript, you can just ignore trailing elements you don’t care about:

Or other elements:

Tuple destructuring

Tuples may be destructured like arrays; the destructuring variables get the types of the corresponding tuple elements:

It’s an error to destructure a tuple beyond the range of its elements:

As with arrays, you can destructure the rest of the tuple with ... , to get a shorter tuple:

Or ignore trailing elements, or other elements:

Object destructuring

You can also destructure objects:

This creates new variables a and b from o.a and o.b . Notice that you can skip c if you don’t need it.

Like array destructuring, you can have assignment without declaration:

Notice that we had to surround this statement with parentheses. JavaScript normally parses a { as the start of block.

You can create a variable for the remaining items in an object using the syntax ... :

Property renaming

You can also give different names to properties:

Here the syntax starts to get confusing. You can read a: newName1 as ” a as newName1 ”. The direction is left-to-right, as if you had written:

Confusingly, the colon here does not indicate the type. The type, if you specify it, still needs to be written after the entire destructuring:

Default values

Default values let you specify a default value in case a property is undefined:

In this example the b? indicates that b is optional, so it may be undefined . keepWholeObject now has a variable for wholeObject as well as the properties a and b , even if b is undefined.

Function declarations

Destructuring also works in function declarations. For simple cases this is straightforward:

But specifying defaults is more common for parameters, and getting defaults right with destructuring can be tricky. First of all, you need to remember to put the pattern before the default value.

The snippet above is an example of type inference, explained earlier in the handbook.

Then, you need to remember to give a default for optional properties on the destructured property instead of the main initializer. Remember that C was defined with b optional:

Use destructuring with care. As the previous example demonstrates, anything but the simplest destructuring expression is confusing. This is especially true with deeply nested destructuring, which gets really hard to understand even without piling on renaming, default values, and type annotations. Try to keep destructuring expressions small and simple. You can always write the assignments that destructuring would generate yourself.

The spread operator is the opposite of destructuring. It allows you to spread an array into another array, or an object into another object. For example:

This gives bothPlus the value [0, 1, 2, 3, 4, 5] . Spreading creates a shallow copy of first and second . They are not changed by the spread.

You can also spread objects:

Now search is { food: "rich", price: "$$", ambiance: "noisy" } . Object spreading is more complex than array spreading. Like array spreading, it proceeds from left-to-right, but the result is still an object. This means that properties that come later in the spread object overwrite properties that come earlier. So if we modify the previous example to spread at the end:

Then the food property in defaults overwrites food: "rich" , which is not what we want in this case.

Object spread also has a couple of other surprising limits. First, it only includes an objects’ own, enumerable properties . Basically, that means you lose methods when you spread instances of an object:

Second, the TypeScript compiler doesn’t allow spreads of type parameters from generic functions. That feature is expected in future versions of the language.

using declarations

using declarations are an upcoming feature for JavaScript that are part of the Stage 3 Explicit Resource Management proposal. A using declaration is much like a const declaration, except that it couples the lifetime of the value bound to the declaration with the scope of the variable.

When control exits the block containing a using declaration, the [Symbol.dispose]() method of the declared value is executed, which allows that value to perform cleanup:

At runtime, this has an effect roughly equivalent to the following:

using declarations are extremely useful for avoiding memory leaks when working with JavaScript objects that hold on to native references like file handles

or scoped operations like tracing

Unlike var , let , and const , using declarations do not support destructuring.

null and undefined

It’s important to note that the value can be null or undefined , in which case nothing is disposed at the end of the block:

which is roughly equivalent to:

This allows you to conditionally acquire resources when declaring a using declaration without the need for complex branching or repetition.

Defining a disposable resource

You can indicate the classes or objects you produce are disposable by implementing the Disposable interface:

await using declarations

Some resources or operations may have cleanup that needs to be performed asynchronously. To accommodate this, the Explicit Resource Management proposal also introduces the await using declaration:

An await using declaration invokes, and awaits , its value’s [Symbol.asyncDispose]() method as control leaves the containing block. This allows for asynchronous cleanup, such as a database transaction performing a rollback or commit, or a file stream flushing any pending writes to storage before it is closed.

As with await , await using can only be used in an async function or method, or at the top level of a module.

Defining an asynchronously disposable resource

Just as using relies on objects that are Disposable , an await using relies on objects that are AsyncDisposable :

await using vs await

The await keyword that is part of the await using declaration only indicates that the disposal of the resource is await -ed. It does not await the value itself:

await using and return

It’s important to note that there is a small caveat with this behavior if you are using an await using declaration in an async function that returns a Promise without first await -ing it:

Because the returned promise isn’t await -ed, it’s possible that the JavaScript runtime may report an unhandled rejection since execution pauses while await -ing the asynchronous disposal of x , without having subscribed to the returned promise. This is not a problem that is unique to await using , however, as this can also occur in an async function that uses try..finally :

To avoid this situation, it is recommended that you await your return value if it may be a Promise :

using and await using in for and for..of statements

Both using and await using can be used in a for statement:

In this case, the lifetime of x is scoped to the entire for statement and is only disposed when control leaves the loop due to break , return , throw , or when the loop condition is false.

In addition to for statements, both declarations can also be used in for..of statements:

Here, x is disposed at the end of each iteration of the loop , and is then reinitialized with the next value. This is especially useful when consuming resources produced one at a time by a generator.

using and await using in older runtimes

using and await using declarations can be used when targeting older ECMAScript editions as long as you are using a compatible polyfill for Symbol.dispose / Symbol.asyncDispose , such as the one provided by default in recent editions of NodeJS.

Nightly Builds

How to use a nightly build of TypeScript

The TypeScript docs are an open source project. Help us improve these pages by sending a Pull Request ❤

Daniel Rosenwasser  (58)

Last updated: Aug 23, 2024  

IMAGES

  1. How to check both undefined and null in typescript?

    typescript undefined assignment

  2. Typescript's types

    typescript undefined assignment

  3. How to easily make a new type by removing null or undefined values from

    typescript undefined assignment

  4. TypeScript undefined

    typescript undefined assignment

  5. NodeJS : Typescript undefined constant during debugging session

    typescript undefined assignment

  6. 💥 Typescript Understanding Null vs Undefined

    typescript undefined assignment

COMMENTS

  1. How to assign string

    42. The typescript compiler performs strict null checks, which means you can't pass a string | undefined variable into a method that expects a string. To fix this you have to perform an explicit check for undefined before calling luminaireReplaceLuminaire(). In your example: return this.selectedSerials.pop();

  2. How to Deal with Optional Things and "Undefined" in TypeScript

    Thankfully, TypeScript is a great tool for helping you deal with it and writing better code in the process. What's undefined? A project set up with TypeScript's strict flag will check for all kinds of potential issues in your code. I recommend letting TypeScript be as strict as you can. undefined typically shows up in a handful of key places:

  3. Type 'undefined' is not assignable to type in TypeScript

    TypeScript is basically telling us that the emp.salary property might have a value of undefined which is not compatible with the type of the salary variable which only expects a number. ... In the if statement, we check if the emp.salary property is not equal to undefined and assign the salary variable to the corresponding value.

  4. Nullish Coalescing: The ?? Operator in TypeScript

    Nullish Coalescing: The ?? Operator in TypeScript August 6, 2020. TypeScript 3.7 added support for the ?? operator, which is known as the nullish coalescing operator.We can use this operator to provide a fallback value for a value that might be null or undefined. #Truthy and Falsy Values in JavaScript Before we dive into the ?? operator, let's recall that JavaScript values can either be truthy ...

  5. TypeScript: Documentation

    TypeScript has two special types, null and undefined, that have the values null and undefined respectively. We mentioned these briefly in the Basic Types section. By default, the type checker considers null and undefined assignable to anything. Effectively, null and undefined are valid values of every type.

  6. How to Detect Null and Undefined in Your TypeScript Code

    This can be used to assign a value only if the variable is null. It's less commonly seen, but you might still run into it. Optional Chaining. Another shortcut TypeScript provides for checking for null or undefined is optional chaining. It's used for accessing properties of an object that might be undefined or null. Let's take this type:

  7. Undefined in TypeScript

    Undefined is a primitive value that indicates that the value is not assigned. i.e. whenever we do not explicitly assign a value to a variable, TypeScript assigns the undefined value to it. It is an unintentional absence of any value. Undefined is different from the value null. The null value means we know that it does not have any value.

  8. TypeScript: Documentation

    Type compatibility in TypeScript is based on structural subtyping. Structural typing is a way of relating types based solely on their members. ... that is a string. It does, so the assignment is allowed. The same rule for assignment is used when checking function call arguments: ts. ... undefined, null, and never assignability. The following ...

  9. Set a default value if Null or Undefined in TypeScript

    You can also use the logical OR (||) operator to provide a default value if a variable is null or undefined. index.ts. const role: string | null = null; const result = role || 'designer'; console.log(result); The code for this article is available on GitHub. The logical OR (||) operator returns the value to the right if the value to the left is ...

  10. How to dynamically assign properties to an object in TypeScript

    Solution 1: Explicitly type the object at declaration time. This is the easiest solution to reason through. At the time you declare the object, go ahead and type it, and assign all the relevant values: type Org = {. name: string. } const organization: Org = {. name: "Logrocket" } See this in the TypeScript Playground.

  11. TypeScript Null & Undefined

    TypeScript Null & Undefined. TypeScript has a powerful system to deal with null or undefined values. By default null and undefined handling is disabled, and can be enabled by setting strictNullChecks to true. The rest of this page applies for when strictNullChecks is enabled.

  12. TypeScript: Playground Example

    Nullish Coalescing. The nullish coalescing operator is an alternative to || which returns the right-side expression if the left-side is null or undefined. In contrast, || uses falsy checks, meaning an empty string or the number 0 would be considered false. A good example for this feature is dealing with partial objects which have defaults when ...

  13. Object is possibly 'undefined' error in TypeScript [Solved]

    The logical AND (&&) operator makes sure the address property isn't undefined, that num exists on the object and is a number before comparing it to the number 10.. This is needed because if the reference is nullish (null or undefined), the optional chaining operator (?.) will return undefined and TypeScript doesn't allow us to compare undefined to a number.

  14. Null Vs Undefined in TypeScript

    Undefined is the default value for uninitialized variables. Whenever we declare a variable without initializing it with a value, TypeScript initializes it as undefined. But TypeScript never assigns null to any variable. We have to assign Null to variable to make it null. The following example declares the variable foo. We have not given it any ...

  15. "Object is possibly 'undefined'." in TypeScript

    The caveat to this solution is that the responsibility for ensuring obj is defined is now only yours and not the compiler's. If you change the preceding code and obj truly is possibly undefined, then the type assertion will still suppress the error, and you'll have issues at runtime. The other solution is to change what you're doing so that the ...

  16. TypeScript: Documentation

    Null- and undefined-aware types. TypeScript has two special types, Null and Undefined, that have the values null and undefined respectively. Previously it was not possible to explicitly name these types, but null and undefined may now be used as type names regardless of type checking mode.. The type checker previously considered null and undefined assignable to anything.

  17. Undefined value after assignment in Typescript

    The model is undefined after the assignment because it is looking for a Pascal-cased property in the JSON, which doesn't exist, for example: this.sessionJson.Email = survey.Email; After storing the response object in survey, all its properties are in camelCase, so in reality if you want to access survey's objet e-mail property you should do:

  18. callback

    On line 3, TS complains that 'a' is possibly undefined. As far as I can see, it must be defined in a single-threaded environment, as the ternary operator eliminates the possibility that it is undefined. I think that the Array.map callback must be the culprit somehow, because if the third line is instead. const b = a !== undefined ? a[2] : 0;

  19. TypeScript: Documentation

    var declarations. Declaring a variable in JavaScript has always traditionally been done with the var keyword. var a = 10; As you might've figured out, we just declared a variable named a with the value 10. We can also declare a variable inside of a function: function f() {.