Skip to content
typescript

How to solve 'Object is possibly undefined' error in TypeScript?

Jun 9, 2022Abhishek EH5 Min Read
How to solve 'Object is possibly undefined' error in TypeScript?

If you are new to TypeScript, you might have faced one of the following errors:

1Object is possibly 'undefined'.ts(2532)
1Argument of type 'string | undefined' is not assignable to parameter of type 'string'.
2 Type 'undefined' is not assignable to type 'string'.ts(2345)

Replicating the issue

Before fixing the issue, let's see how this issue can be replicated. Consider the following code:

1type Employee = {
2 name: string
3 address?: {
4 street?: string
5 city?: string
6 }
7}
8
9const employee1: Employee = { name: "Abhi" }
10
11// ⛔️ Error: Object is possibly 'undefined'.ts(2532)
12
13console.log(employee1.address.city)

If you run the following code in a TypeScript environment, you will get the above error.

Let's understand why the error occurs. The reason for the error is, that while declaring the employee1 object, we are passing only the name property. We are not passing the address property and hence TypeScript knows that employee.address will result in undefined and it cannot access the city from undefined.

We can replicate the second error using the following code:

1function printName(value: string) {
2 console.log(value)
3}
4
5let fullName = "Abhi" as string | undefined
6
7// ⛔️ Error: Argument of type 'string | undefined' is not assignable to parameter of type 'string'.
8// Type 'undefined' is not assignable to type 'string'.ts(2345)
9printName(fullName)

In the above code, we are defining fullName as either a string or undefined and passing it to a function, which expects a string. Since undefined values cannot be converted to a string, we get the error.

It may look silly why fullName needs to be assigned a type of undefined. It is just done for replicating the issue. In real scenarios, there can be variables received as function parameters and passed to another function, and you receive this error.

Solutions

There are multiple solutions to fix this error.

Using if conditions

You can add a if condition around the line where the error comes and fix it as shown below.

1type Employee = {
2 name: string
3 address?: {
4 street?: string
5 city?: string
6 }
7}
8
9const employee1: Employee = { name: "Abhi" }
10
11if (employee1.address) {
12 console.log(employee1.address.city)
13}
1function printName(value: string) {
2 console.log(value)
3}
4
5let fullName = "Abhi" as string | undefined
6
7if (fullName) {
8 printName(fullName)
9}

Now the code will execute only if the value exists and will not result in any error.

Using the 'as' keyword

If you are sure about the type of the value, you can type cast it using the as keyword as shown below:

1function printName(value: string) {
2 console.log(value)
3}
4
5let fullName = "Abhi" as string | undefined
6
7printName(fullName as string)

Using the non-null assertion operator (!)

If you are sure that the value will never be null, then you can use an exclamation mark (!) next to the variable to tell TypeScript that the value can never be null at this place.

1type Employee = {
2 name: string
3 address?: {
4 street?: string
5 city?: string
6 }
7}
8
9const employee1: Employee = { name: "Abhi" }
10
11console.log(employee1.address!.city)
1function printName(value: string) {
2 console.log(value)
3}
4
5let fullName = "Abhi" as string | undefined
6
7printName(fullName!)

Of course, the first code will result in error during run-time since address is undefined. So non-null assertion operator needs to be used with caution. After all, TypeScript is here to warn us from potential bugs, not to scare us!

Using optional chaining operator (?)

You can use optional chaining as highlighted below to access properties that may not exist.

1type Employee = {
2 name: string
3 address?: {
4 street?: string
5 city?: string
6 }
7}
8
9const employee1: Employee = { name: "Abhi" }
10
11console.log(employee1?.address?.city)

The above code will not break like the previous one. It will check if the city is present and print it. If it is not present, it will print undefined.

Using the logical OR (||) operator

You can pass a default value to the function if you think the value can be undefined as shown below:

1function printName(value: string) {
2 console.log(value)
3}
4
5let fullName = "Abhi" as string | undefined
6
7printName(fullName || "default-value")

Now if the fullName is having a falsy value, then it will pass the 'default-value'.

Using nullish coalescing operator (??)

Nullish coalescing is similar to logical OR operator except that it evaluates to the right side operand only if the left side operand is null or undefined, whereas logical OR (||) operator does it for other falsy values like an empty string, 0, false, etc.

You can use nullish coalescing operator as shown below:

1function printName(value: string) {
2 console.log(value)
3}
4
5let fullName = "Abhi" as string | undefined
6
7printName(fullName ?? "default-value")

These are the few ways in which you can fix the error. You can use any one of them based on your use case.

Do follow me on twitter where I post developer insights more often!

Leave a Comment

© 2022 CodingDeft.Com