In TypeScript 2, you can use the undefined type to check for undefined values.

If you declare a variable as:

let uemail : string | undefined;

Then you can check if the variable uemail is undefined like this:

if(uemail === undefined)
{

}
Answer from ashish on Stack Overflow
🌐
Tim Mousk
timmousk.com › blog › typescript-check-for-undefined
How To Check For Undefined In TypeScript? – Tim Mouskhelichvili
March 8, 2023 - As you can see, checking for undefined in TypeScript is simple. You just need to do a condition check, and voila. Here are other TypeScript tutorials for you to enjoy: ... Hello! I am Tim Mouskhelichvili, a Freelance Developer & Consultant from Montreal, Canada. I specialize in React, Node.js ...
🌐
W3Schools
w3schools.com › typescript › typescript_null.php
TypeScript Null & Undefined
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. let value: string | undefined | null = null; value = 'hello'; value = undefined; Try it Yourself » · When strictNullChecks is enabled, TypeScript requires values to be set unless undefined is explicitly added to the type.
🌐
Akos Komuves
akoskm.com › how-to-solve-variable-is-possibly-undefined-in-typescript-even-when-its-defined
How to solve ”variable is possibly undefined” in TypeScript - even when it’s defined | Akos Komuves
The solution is to either explicitly check for the value before usage or pass the value as a required argument to functions, ensuring type safety and preventing runtime errors. You just learned how you could both improve the readability of your ...
🌐
2ality
2ality.com › 2013 › 04 › check-undefined
Checking for undefined: === versus typeof versus falsiness
Recommendation: check for undefined either via === undefined or via falsiness. It is normally more important for code to be easy to understand than to be completely safe.
🌐
DEV Community
dev.to › kais_blog › how-to-check-for-undefined-in-javascript-typescript-3men
How to Check For Undefined in JavaScript / TypeScript - DEV Community
January 2, 2021 - So, I suggest that you always use the typeof operator if you are checking for undefined. Let's move your learning forward together! Follow me on Twitter for your daily dose of developer tips. Thanks for reading my content! This post was originally published at kais.blog. ... Have a look at the new syntax sugar here: developer.mozilla.org/en-US/docs/W... ... Thanks for this addition. Nullish coalescing operator (??) and optional chaining (?.) are indeed very useful. Nevertheless, the real check for undefined is the one I've described.
🌐
TypeScript
typescriptlang.org › docs › handbook › release-notes › typescript-2-0.html
TypeScript: Documentation - TypeScript 2.0
So, whereas T and T | undefined are considered synonymous in regular type checking mode (because undefined is considered a subtype of any T), they are different types in strict type checking mode, and only T | undefined permits undefined values. The same is true for the relationship of T to ...
Find elsewhere
🌐
Rampatra
blog.rampatra.com › null-vs-undefined-in-typescript-or-javascript-how-to-check-for-both-at-once
!== null vs !== undefined in Typescript or Javascript, how to check for both at once?
if (value != null) { // Do something if value is not null or undefined } Prefer strict equality checks (!== or ===) for better type safety and clarity.
🌐
GeeksforGeeks
geeksforgeeks.org › typescript › how-to-check-null-and-undefined-in-typescript
How to check null and undefined in TypeScript ? - GeeksforGeeks
July 23, 2025 - We can use typeof or '==' or '===' to check if a variable is null or undefined in typescript.
🌐
Reddit
reddit.com › r/typescript › how check for undefined in conditional type
r/typescript on Reddit: How check for undefined in conditional type
November 14, 2023 -

This code do not work at all, but not sure why.

type IsUndefined<T> = T extends undefined ? 1 : 0;

For example:

type IsTypeUndefined = IsUndefined<number | undefined>;
// This returns: 1 | 0

Is there a way for check if a type is undefined in a conditional?

🌐
Webtips
webtips.dev › solutions › check-undefined-in-typescript
How to Correctly Check Undefined in TypeScript - Webtips
September 21, 2022 - To check for undefined values in TypeScript, you need to use the strict equal operator against the undefined keyword.
🌐
Zipy
zipy.ai › blog › debug-typescript-null-or-undefined-value-errors
Solving Typescript Null & Undefined Errors: Expert Tips
February 28, 2024 - Efficiently debug & fix TypeScript null or undefined value errors. Expert tips for handling & resolving errors in TypeScript.
🌐
Upmostly
upmostly.com › home › typescript › how to detect null and undefined
How to Detect Null and Undefined in Your TypeScript Code - Upmostly
March 28, 2023 - Another way to check for null or undefined is to use the nullish coalescing operator (??), which was introduced in TypeScript 3.7.
🌐
GitBook
basarat.gitbook.io › typescript › recap › null-undefined
Null vs. Undefined | TypeScript Deep Dive
You should use strict mode ... and in fact the TS compiler will insert it for you if you use modules ... more on those later in the book so you don't have to be explicit about it :) So to check if a variable is defined or not at a global level you normally use typeof: ... if (typeof someglobal !== 'undefined') { // someglobal is now safe to use console.log(someglobal); } Because TypeScript gives you the opportunity to document your structures separately from values instead of stuff like:
🌐
Bobby Hadz
bobbyhadz.com › blog › react-null-or-undefined-check
Check if a Variable is Null or Undefined in React | bobbyhadz
We used the strict equality === operator for the examples, however, there is a more concise way to check if a variable is equal to null or undefined, using loose equality ==. ... Copied!import {useEffect, useState} from 'react'; export default ...
🌐
Reddit
reddit.com › r/typescript › typescript says object is possibly 'undefined' for an object property, even after checking/narrowing if the property exists.
r/typescript on Reddit: Typescript says object is possibly 'undefined' for an object property, even after checking/narrowing if the property exists.
April 3, 2021 -

Hello. I have a simple question, most likely some rookie mistake I am making, but not exactly sure why it's happening.

I have a simple interface IPerson, a person object, and finally a function searchPerson that lets you search a person's hobbies if they have any.

 

TypeScript Playground link

 

interface IPerson {
    skills?: {
        name: string;
    }[];
    hobbies?: {
        name: string;
    }[];
}

const person: IPerson = {
    hobbies: [
        { name: 'programming' },
        { name: 'gaming' },
    ]
};

const searchPerson = ({ type, search }: { type: keyof IPerson, search: string }) => {
    if (type === 'hobbies') {
        if (person[type]) {
            person[type].find(hobby => hobby.name === search); // <= error is here
        }
    }
};

 

All seems to work as intended, except for the fact that Typescript is complaining that Object is possibly 'undefined'. at the end of my function at the person[type].find(...) part, even though just the line above I am checking if if (person[type) is not undefined.

In the past I have dealt with something similar. For example, instead of keyof IPerson as type parameter of the function, I was using an arbitrary string which was causing issues, but here I am clearly telling TypeScript that type should be a key of IPerson, and since hobbies is an optional parameter I am checking if (person[type]) exists first. Yet it's still telling me that it's possibly undefined.

I am kinda confused, anyone has an idea what is happening here or can point me in the right direction? Cheers!

EDIT: Forgot to mention, I am aware that I can use optional chaining (person[type]?.find(...)) or non-null assertion operator (person[type]!.find(...)) but I am trying to understand why this is treated as undefined, rather than looking for a workaround.

🌐
Atomic Spin
spin.atomicobject.com › optional-undefined-typescript
How to Deal with “Optional” and “Undefined” in TypeScript
November 25, 2024 - 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.
Top answer
1 of 2
5

You can make throwIfUndefined an assertion function to narrow the type of its argument to something that does not include undefined in its domain. An assertion function has an assertion type predicate of the form asserts x is Y as its return type, where x is the name of one of the function's parameters, and Y is the subtype of typeof X that we narrow x to assuming the function returns successfully. Assertion functions cannot return a defined value; they are basically void-returning functions.

For throwIfUndefined, here's the normal way to do it, as a function statement:

function throwIfUndefined<T>(x: T | undefined): asserts x is T {
    if (typeof x === "undefined") throw new Error("OH NOEZ");
}

You can also write it as an arrow function, although you need to explicitly annotate the variable with its type for the control flow analysis to happen correctly:

const throwIfUndefined: <T, >(x: T | undefined) => asserts x is T = x => {
    if (typeof x === "undefined") throw new Error("OH NOEZ");
}

Either way should work:

const Index = ({ params }: { params: { myVar: string | undefined } }) => {
    const { myVar } = params // myVar: string | undefined
    // myVar.toUpperCase // <-- error, Object is possibly 'undefined'
    throwIfUndefined(myVar);
    return myVar.toUpperCase() // no error now
}

try {
    console.log(Index({
        params: {
            myVar: Math.random() < 0.5 ? "hello" : undefined
        }
    })) // 50% "HELLO" 
} catch (e) {
    console.log(e); // 50% "OH NOEZ"
}

Playground link to code

2 of 2
0

You could skip definedOrRedirect and use an explicit check:

export const loader: LoaderFunction = async ({ params }) => {
  const { myVar } = params; // myVar: string | undefined 
  if (myVar == undefined) {
    return redirect("/");
  }
  return fetchSomething(myVar); // myVar: string
}

Or you could keep definedOrRedirect and declare it with an assertion as jcalz suggests:

function definedOrRedirect(variable, path): asserts variable is string
{
  if (variable == undefined) {
    return redirect(path);
  }
}

export const loader: LoaderFunction = async ({ params }) => {
  const { myVar } = params; // myVar: string | undefined 
  definedOrRedirect(myVar, "/");
  return fetchSomething(myVar); // myVar: string
}
🌐
GitHub
github.com › microsoft › TypeScript › issues › 13195
Distinguish missing and undefined · Issue #13195 · microsoft/TypeScript
December 28, 2016 - TypeScript Version: 2.1.4 Code Current, with --strictNullChecks on, the typescript compiler seems to treat interface Foo1 { bar?: string; } and interface Foo2 { bar?: string | undefined; } as being the same type - in that let foo: Foo1 =...
Published   Dec 28, 2016