Error ts2532 object is possibly undefined

This article goes over 5 methods to solve a problem like TS2532: Object is possibly ‘undefined’. You can use IF conditions, logical operator, non-null assertion and more.

Have you ever tried to access a property in an object, but you get a TypeScript error message such as:


TS2532: Object is possibly 'undefined'.

Or maybe, you want to pass a variable in a function


function validateToken(token: string) {
  return token;
}

const token = 'kjadj' as string | undefined;

validateToken(token);

and you end up getting a TypeScript error message like this:


TS2322: Type 'string | undefined' is not assignable to type 'string'. Type 'undefined' is not assignable to type 'string'.

This happens because TypeScript expects a specific value type but you’re providing an incorrect value type. If you like to learn more about JavaScript value types, feel free to check out this article, “JavaScript data types: Intro“.

In this article, I’m going to show you 5 different methods to handle this situation.

Method #1: Use IF conditions


if (token) {
  validateToken(token);
}

The example above checks if the variable, token, is a falsy or truthy value.

This works because we’ve originally said that token maybe be a string value or undefined.

I highly recommend you to be a little bit more specific on your check. Use the typeof keyword and make sure its the right JavaScript value type.


if (typeof token === 'string') {
  validateToken(token);
}

Method #2: Use the OR logical operator

Another method is to use OR operator (||).


validateToken(token || 'default-token');

If token doesn’t meet validateToken() argument requirement, than pass a fallback value.

In the example above, if the value of token is undefined, then the string "default-token" will be used as the fallback.

Method #3: Use the keyword as

The keyword as, can be used to let TypeScript know, that you know the value is going to be whatever value type it expects.

Here’s an example:


validateToken(token as string)

In the example above, I’m passing token, and letting TypeScript know that even though the variable may be undefined; at this point of the app, it will be a string. So it has nothing to worry about.

Method #4: Use ! non-null assertion operator

After a variable is being used, you may add the exclamation mark (!) after the variable.


validateToken(token!);

This similar to method #3. Sometimes the TypeScript compiler isn’t able to determine what type of value it may at a certain point.

By adding the exclamation mark (!) at the end, you let the TypeScript compiler that there is no way this variable will be undefined or null.

Method #5: Use ?? nullish coalescing operator


validateToken(token ?? 'default-token');

This method is very similar to method #2, OR logical operator (||). The difference is that the OR logical operator checks for falsy values.

Falsy values are false, undefined, null, 0, NaN, and a empty string.

Nullish coalescing operator (??) only checks for undefined or null.

Oh wow, you’ve made it this far! If you enjoyed this article perhaps like or retweet the thread on Twitter:

In TypeScript, when a variable or object property is defined as optional and another primitive type, you may get an error when you try to use it.

Here are 5 methods to solve this issue check out the 🧵 pic.twitter.com/M9chovpMjv

— ʀᴜʙᴇɴ (@rleija_) September 26, 2020

I like to tweet about TypeScript and post helpful code snippets. Follow me there if you would like some too!

Table of Contents

Hide

  1. What is Object is possibly ‘undefined’ error in TypeScript?
  2. How to fix Object is possibly ‘undefined’ error in TypeScript
    1. Solution 1: Using Optional chaining
    2. Solution 2: Checking undefined
    3. Solution 3: Using the AND / OR logical operator
    4. Solution 4: Using ?? nullish coalescing operator
  3. Conclusion

The Object is possibly ‘undefined’ occurs when we try to access a property of an object that is undefined. Sometimes few properties in TypeScript can be defined as optional and it may lead to this error.

In this article, we will look at what is Object is possibly ‘undefined’ error in TypeScript and how to resolve this error with examples.

As the error itself suggests that some of the property in the Object is undefined or you have made that as an optional in the TypeScript.

Let us reproduce this issue with a simple example.

type Book = {
  genre?: { 
    language?: string;
    author?: string;
  };
};

const b1: Book = {};
// Now if language is optional and not defined.
p1.genre.language; 

Output

// Error: Object is possibly 'undefined'.ts(2532)

How to fix Object is possibly ‘undefined’ error in TypeScript

There are several ways to fix the error. Let us explore the best approaches to avoid this issue.

Solution 1: Using Optional chaining

The Optional chaining refers to the question mark dot (?.) in Typescript. It is used while accessing a nested property of an object.

The ?. operator is like the . chaining operator, except that instead of causing an error if a reference is nullish (null or undefined), the expression short-circuits with a return value of undefined.

We can use this even with function calls and instead of throwing error it returns undefined if the given function does not exist.

After using the optional chain operator, it will not throw any error but the return value will be undefined as shown in the below example.

type Book = {
  genre?: { 
    language?: string;
    author?: string;
  };
};

const b1: Book = {};
// Now, if language is optional and not defined.
const resultVal = b1?.genre?.language;
console.log(resultVal)

Output

undefined 

*Fact Check: This approach is used in remote method invocation or API to read data.

Solution 2: Checking undefined

One of the easiest ways of checking the value for correctness is before assessing the property. There are multiple ways to do this. Let us discuss them.

A). Using if

type Book = {
  genre?: { 
    language?: string;
    author?: string;
  };
};

const b1: Book = {};
if (b1.genre != undefined) {
  console.log(b1.genre.language?.toUpperCase);
  console.log(b1.address.author?.toUpperCase);
}

This method is self-explanatory as we check the value before performing any operation.

B). Using non-null assertion

We use it when we are convinced that the property value cannot be null. It can be undefined but not null.

type Book = {
  genre?: { 
    language?: string;
    author?: string;
  };
};

const b1: Book = {
  genre: {
    language: 'English',
    author: 'Shakespeare',
  },
};

console.log(b1.genre!.language); // English

Solution 3: Using the AND / OR logical operator

This is similar to providing fallback value. In case we find the value as undefined no error is thrown. Instead, it returns the fallback value. 

validateBook(book || 'default-Book');
type Book = {
  genre?: { 
    language?: string;
    author?: string;
  };
};

const b1: Book = {};
if (b1.genre && b1.genre.language) {
  console.log(b1.genre.language);
}

Here, we have shown this by calling a function called validateBook and passing a reference to the book. If the value returned is undefined, default-Book will be returned instead of an error.

Difference between || and ??

The main difference is:

  • || returns the first true value.
  • ?? returns the first defined value.

In other words, || does not differentiate between false, 0, an empty string, and null/undefined. They are all falsy values. If the first argument of || is a false value, we’ll get the second argument as the output.

Solution 4: Using ?? nullish coalescing operator

The nullish coalescing operator is used as two question marks ??.

The nullish coalescing operator (??) is a logical operator that returns its right-hand side operand when its left-hand side operand is null or undefined, and otherwise returns its left-hand side operand.

As it treats null and undefined likewise, we declare that an expression is “defined” when it’s neither null nor undefined. In other words, it returns the first parameter if it’s not null/undefined. else, the second one.

The result of x ?? y is:

  • if x is defined, then x,
  • if x isn’t defined, then y.
// Example in case of null
const foo = null ?? 'default string';
console.log(foo);

// Example in case of undefined
const bar = undefined ?? 'My default value';
console.log(bar);

// Example in case of function
function initializeAudio() {
  let volume = localStorage.volume || 0.5;
  console.log(volume)
}

initializeAudio();

Output

default string
My default value
0.5 

Conclusion

We can safely assume that type check is the best way to stop the Object is possibly ‘undefined’ error from occurring. Instead of comparing to undefined, we can use the optional chaining, nullish coalescing, AND, OR operators. Among them, it is better to go with the nullish coalescing operator as it is more efficient.

Related Tags
  • AND operator,
  • coalescing operator,
  • Optional chaining,
  • OR operator,
  • undefined

Sign Up for Our Newsletters

Get notified on the latest articles

By checking this box, you confirm that you have read and are agreeing to our terms of use regarding the storage of the data submitted through this form.

Cover image for Object is possibly 'undefined'.ts(2532)

Senichi

Let me tell you now, there is no solution, but there is a method of deal with the error.

Microsoft team member for Typescript said in a related trend that «This is working as intended».

Many developers are talking about this from different use cases as arrays, function callbacks, string values, html elements inside a React components (my case), and the list grows and grows…

I could found suggested solution that it doesn’t worked, as background is that «The type system would effectively have to make a distinction between empty and non-empty arrays which isn’t something we track».

So, a few links where this is discussed:

  1. Null References: The Billion Dollar Mistake
  2. How can I solve the error ‘TS2532: Object is possibly ‘undefined’?
  3. False «Property does not exist on type ‘never'» when changing value inside callback with strictNullChecks
  4. ‘Property does not exist on type ‘never’
  5. TypeScript does not expect variable change in forEach
  6. TS2531: Object is possibly ‘null’
  7. How to suppress «error TS2533: Object is possibly ‘null’ or ‘undefined'»?
  8. Getting Object is possibly ‘undefined’ in typescript react
  9. Annotate immediately-invoked functions for inlining flow control analysis

Suppressing errors

  • the deal

Suppress errors in .ts files using ’// @ts-ignore’ comments

A // @ts-ignore comment suppresses all errors that originate on the following line. It is recommended practice to have the remainder of the comment following @ts-ignore explain which error is being suppressed.

Please note that this comment only suppresses the error reporting, and we recommend you use this comments very sparingly.

How I solve this

  • «the right combination of types and assertion»

So, TypeScript also has a special syntax for removing null and undefined from a type without doing any explicit checking. Writing ! after any expression is effectively a type assertion that the value isn’t null or undefined:

# case
const textElementRef = useRef();
// this provokes the error in the next line
const text = textElementRef.current;
// Object is possibly 'undefined'.ts(2532)'
const textWidth = text.offsetWidth;

# what I was trying
const textElementRef = useRef();
const text = textElementRef.current; 
const textWidth = text!.offsetWidth; <-- type assertion
// causing : Property 'offsetWidth' does not exist on type 'never'.ts(2339)

# then I have to change the useRef definition too
const textElementRef = useRef<HTMLSpanElement>(null);
const text = textElementRef.current!; <-- type assertion
const textWidth = text.offsetWidth;

Enter fullscreen mode

Exit fullscreen mode

Понравилась статья? Поделить с друзьями:
  • Error ts18002 the files list in config file tsconfig json is empty
  • Error ts1345 an expression of type void cannot be tested for truthiness
  • Error ts1192 module fs has no default export
  • Error ts1086 an accessor cannot be declared in an ambient context
  • Error ts1056 accessors are only available when targeting ecmascript 5 and higher