TypeScript Undefined

May 11


Types are great unless they don’t know what they are.

Have you ever seen an issue like this?

TS2532: Object is possibly 'undefined'.

There are several ways to deal with this issue.

Lets set up an example

function returnString (str: string) {
    return string

const val = 'qwerty' as string | undefined;

Here you have a function that is expecting a string and a value that is a string or undefined. While you know it’s a string, typescript knows it could be undefined as well.

If you try this


It will throw the error

TS2532: Object is possibly 'undefined'.

How do you deal with this?

1. Check with an IF

The first method to ensure that a value is not undefined is via an if

if (val) {

This will only log if value is defined as something. It is the simplest check. This can still have issues though. What if val is a number?

if (typeof val === 'string') {

This is a safer check, now you know that you not only have a defined value but it is also a string.

2. Set a default

TypeScript is smart enough to know when a value won’t fit the type required. In that case you can set a default.

returnString(val || 'asdf')

In this case you will get the string in val or the default of asdf if val is not a string.

Another way to accomplish the same thing is to check for falsy values. false, undefined, null, 0, NaN

returnString(val ?? 'asdf')

If the value is falsy then the default will be used.

3. Tell TypeScript you know best

There are two methods of letting the compiler know that you are certain the value of a variable will be what you expect.

Say it with !


The ! is known as the non-null assertion operator. It lets the compiler know there is no way the value will be undefined or null.

The second way is to tell it the type as you use the value.

returnString(val as string)

Again, this is telling the compiler you know best and there is no way this is anything but a string.

Use these with caution.