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
🌐
TypeScript
typescriptlang.org › docs › handbook › release-notes › typescript-2-0.html
TypeScript: Documentation - TypeScript 2.0
The compiler checks that variables are definitely assigned by performing control flow based type analysis. See later for further details on this topic. Optional parameters and properties automatically have undefined added to their types, even when their type annotations don’t specifically include undefined. For example, the following two types are identical: ... A property access or a function call produces a compile-time error if the object or function is of a type that includes null or undefined.
🌐
Omarileon
omarileon.me › blog › typescript-null-undefined
mari. | How to Detect Null and Undefined in Your TypeScript Code
February 27, 2024 - The most straightforward way of checking is of course the equality operator. const myValue = maybeNullOrUndefined(); if (myValue === null) console.log('Null!'); if (myValue === undefined) console.log('Undefined!');
🌐
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. This operator returns the left-hand side of the expression if it’s not null or undefined, and the right-hand ...
🌐
GitBook
basarat.gitbook.io › typescript › recap › null-undefined
Null vs. Undefined | TypeScript Deep Dive
In strict mode if you use foo and foo is undefined you get a ReferenceError exception and the whole call stack unwinds. 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: Copy · 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: Copy ·
Top answer
1 of 4
3

Let me try to explain you what is typescript thinks about your code and how it acts:


class TestClass {
   // this is the worst possible getter for a typescript compiler
   // the random nature of the getter deceives both the compiler and the developer
    get person(): Person | undefined {
        if (Math.random() > 0.5) return undefined
        return { name: 'Bob', age: 35 }
    }

    get test() {
        if (!this.person) return undefined
        // In here TS compiler thinks that accessing this.person.name 
        // is safe because the above line has a guard for it.
        // But it will throw runtime errors by %50 chance
        // Note that TS doesn't aware of its randomness here
        const name = this.person.name //
        // If we describe this line we call it a local arrow function definition
        // Since it's a definition and also there is no nullability guard in it TS is right about complaining here
        // Since it's a definition it is not deterministic where it 
        // will be called in the code, and the compiler can't be sure whether it is null or not.
        const processPerson = () => this.person.name // Object is possibly 'undefined'.(2532)
        return processPerson()
    }
}

The other answers have already good practices to avoid the error and possible runtime issues.

2 of 4
2

The problem is that your test calls the getter twice, and since the getter randomly returns either undefined or a value, the two lines don't get the same value.

Looks like the first call to the getter gets a value, while the second call gets undefined.

To fix this, call the getter once at the beginning of the test method, and assign the result to a local variable. Then test the local variable instead of calling the getter, like this

test() {
        const subject = this.person;
        if (!subject) return undefined
        const name = subject.name
        const processPerson = () => subject
        return processPerson()
    }
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
}
🌐
Reddit
reddit.com › r/typescript › typescript not acknowledging 'not undefined' assertion
r/typescript on Reddit: Typescript not acknowledging 'not undefined' assertion
November 29, 2023 -

Update: For simplicity, I replicated the original error with simpler code.

Update 2: I got around this by using a type guard for T. Thank u/ritajalilip for the suggestion. I still think Typescript should handle this better though.

As you can see on the screenshot, inside the if statement I'm asserting that x is not undefined. However Typescript is failing to acknowledge and still thinks that x can be undefined.

Any idea of what's going on?

Find elsewhere
🌐
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. By using typescript compiler tcs we transpile typescript code to javascript and then run the javascript file.
🌐
W3Schools
w3schools.com › typescript › typescript_null.php
TypeScript Null & Undefined
When strictNullChecks is enabled, TypeScript requires values to be set unless undefined is explicitly added to the type. Optional chaining is a JavaScript feature that works well with TypeScript's null handling.
🌐
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 - The correct way to check if something is undefined in JavaScript / TypeScript: Use the typeof operator!
🌐
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?

🌐
2ality
2ality.com › 2013 › 04 › check-undefined
Checking for undefined: === versus typeof versus falsiness
Technique 2: compare with void 0. The void operator [2] evaluates its operand, ignores the result and returns undefined. That means that void 0 will always evaluate to undefined. ... if (typeof x === 'undefined') ... This is more verbose and can be slower (though many engines optimize).
🌐
freeCodeCamp
freecodecamp.org › news › the-top-stack-overflowed-typescript-questions-explained
The Most Asked TypeScript Questions on StackOverflow – Handbook for Beginners
July 11, 2022 - By using the non-null assertion operator, the TypeScript compiler will act as if null and undefined are never possible for the value in question. In this case, ref.current. The first line of action you should employ is to find an alternative fix.
🌐
Delft Stack
delftstack.com › home › howto › typescript › undefined checking in typescript
How to Check for Undefined in TypeScript | Delft Stack
February 2, 2024 - The first line sets the data type of variable userEmail as either string or undefined. After setting the datatype, it validates the variable in the if condition. === in TypeScript will allow checking both the variable type as well as its value and performs the desired operation after the validation. If the userEmail is assigned with the string value, the output will be following: Else if it is not assigned with the value, it will be undefined and will be detected first if checked and displays the output as: