TypeScript example

How to check for null or undefined in TypeScript

9 min read Updated Nov 2026 Runs in an isolated runtime
Quick answer

Use if (value == null). It is true for exactly null and undefined, and after it TypeScript narrows the type: in the else branch a string | null | undefined is just a string. For a default value write value ?? fallback, and to read through a value that may be missing write value?.prop. Reach for the ! operator only when you know something the checker can't, because it checks nothing at runtime.

At runtime TypeScript is JavaScript, so the checks themselves are the JavaScript ones: == null, === undefined, ?? and ?.. The JavaScript version of this page covers how they behave. What TypeScript adds is narrowing: the checker reads your if and changes the variable's type inside it. With strict on (or just strictNullChecks), as in most projects, a string | undefined can't be used as a string until a check like that has run, and that is where errors such as Object is possibly 'undefined'. come from.

This page's compiler runs without strict, so it would not report those errors. Every example below is written to pass with strict on as well, and the error messages quoted in the notes come from TypeScript 5.9 with --strict. Each example runs on this page: hit Run, then edit the code and run it again.

1value == null, and the type narrowsRecommended

value == null is the one comparison where loose equality is the right tool: null and undefined are loosely equal to each other and to nothing else, so it catches both missing values and lets 0, "" and false through. TypeScript understands it. After an early return on name == null, the rest of the function sees name as a plain string. The long form, name === null || name === undefined, narrows the same way, and value != null is the positive version.

null-check.ts
function greet(name: string | null | undefined): string {
    // == null is true for null and undefined, and for nothing else
    if (name == null) {
        return "Hello, stranger";
    }
    // From here on TypeScript knows name is a string
    return `Hello, ${name.toUpperCase()}`;
}

console.log(greet("Ada"));
console.log(greet(null));
console.log(greet(undefined));
console.log(JSON.stringify(greet("")));    // "" is a string, not a missing value

// The long form narrows exactly the same way
function lengthOf(text: string | null | undefined): number {
    if (text === null || text === undefined) return -1;
    return text.length;
}
console.log(lengthOf("four"), lengthOf(null), lengthOf(undefined));

// != null keeps the values that are there, 0 included
const readings: (number | null | undefined)[] = [3, null, 0, undefined, 7.5];
for (const r of readings) {
    if (r != null) console.log(r.toFixed(1));
}

Output

greet prints Hello, ADA for a name and Hello, stranger for both null and undefined, while the empty string is still a string and gets "Hello, ". The long form gives 4 -1 -1, and the loop prints 3.0, 0.0 and 7.5: != null keeps the zero. Delete the check in greet and, with strict on, the checker stops at name.toUpperCase() with error TS18049: 'name' is possibly 'null' or 'undefined'. For a parameter typed string | undefined the message is error TS18048: 'name' is possibly 'undefined'. The check is the fix, not a workaround.

2Defaults and safe access: ??, ?. and ??=

Often you don't want a branch, you want a value. a ?? b returns b only when a is null or undefined, and its type drops them: user.nickname ?? user.name is a string, not a string | undefined. a?.b stops at null or undefined and returns undefined, so its type gains undefined, and the two pair up as a?.b ?? fallback. This is the usual fix for Type 'string | undefined' is not assignable to type 'string'.

defaults.ts
interface User {
    name: string;
    nickname?: string;                    // optional: string | undefined
    address?: { city?: string } | null;
    retries?: number;
}

const ada: User = { name: "Ada", retries: 0 };
const bob: User = { name: "Bob", nickname: "Bobby", address: { city: "Oslo" } };
const cy: User = { name: "Cy", address: null };

// ?? turns string | undefined into string
function displayName(user: User): string {
    return user.nickname ?? user.name;
}
console.log(displayName(ada), displayName(bob));

// ?. stops at null or undefined, so user.address?.city is string | undefined
function cityOf(user: User): string {
    return user.address?.city ?? "unknown city";
}
console.log(cityOf(ada), "|", cityOf(bob), "|", cityOf(cy));
console.log(ada.address?.city, cy.address?.city);

// ?? keeps 0; || replaces every falsy value
console.log(ada.retries ?? 3, ada.retries || 3);

// ??= fills in a value only when it is null or undefined
const options: { timeout?: number; retries?: number } = { retries: 0 };
options.timeout ??= 5000;
options.retries ??= 3;
console.log(options);

Output

The output is Ada Bobby, then unknown city | Oslo | unknown city: Ada has no address and Cy's is null, and ?. handles both. On its own, ?. returns undefined for either (undefined undefined). With strict on, writing const nick: string = user.nickname; fails with error TS2322: Type 'string | undefined' is not assignable to type 'string'., and so does return user.address?.city; in a function that returns string. Dropping the ?. (user.address.city) gives error TS18049: 'user.address' is possibly 'null' or 'undefined'. The 0 3 line is why ?? beats || for defaults: || replaced a real 0. Last, ??= filled in the missing timeout and left the 0 retries alone: { retries: 0, timeout: 5000 }.

3Fixing "Object is possibly 'undefined'": find(), Map.get() and friends

The error rarely comes from your own variables. It comes from standard APIs whose return type admits that nothing was found: Array.prototype.find returns T | undefined, Map.prototype.get returns V | undefined, and optional properties and parameters are T | undefined. The fix is the same each time: store the result in a const, check it, and decide what a missing value means. Either return something else, or throw, which also narrows: after the throw, the function can return the value as the full type.

find-and-get.ts
interface Product {
    id: number;
    name: string;
    price: number;
}

const products: Product[] = [
    { id: 1, name: "Keyboard", price: 49 },
    { id: 2, name: "Mouse", price: 19 },
];
const stock = new Map<string, number>([["Keyboard", 12], ["Mouse", 0]]);

// find() returns Product | undefined: check before you read a property
function priceOf(id: number): string {
    const product = products.find((p) => p.id === id);
    if (product === undefined) return `no product ${id}`;
    return `${product.name}: $${product.price}`;
}
console.log(priceOf(2));
console.log(priceOf(9));

// Map.get() returns number | undefined: a missing key is not the same as 0
function stockOf(name: string): string {
    const count = stock.get(name);
    if (count === undefined) return `${name}: not tracked`;
    return `${name}: ${count} in stock`;
}
console.log(stockOf("Mouse"));
console.log(stockOf("Webcam"));

// When a missing value is a bug, throw: the return type stays Product
function getProduct(id: number): Product {
    const product = products.find((p) => p.id === id);
    if (product === undefined) {
        throw new Error(`Product ${id} not found`);
    }
    return product;
}
try {
    console.log(getProduct(1).name);
    console.log(getProduct(3).name);
} catch (err) {
    console.log(err instanceof Error ? err.message : err);
}

Output

priceOf prints Mouse: $19 and no product 9, and stockOf tells a stock of zero (Mouse: 0 in stock) from a key that isn't there (Webcam: not tracked), which a truthiness check on the count would mix up. getProduct prints Keyboard, then throws Product 3 not found. With strict on and the checks removed, these are the messages: products.find(...).name and stock.get("Keyboard").toFixed(0) give error TS2532: Object is possibly 'undefined'., reading product.name on the stored result gives error TS18048: 'product' is possibly 'undefined'., and returning the bare find result from getProduct gives error TS2322: Type 'Product | undefined' is not assignable to type 'Product'. TypeScript names the variable when there is one (TS18048, TS18049) and says "Object" for any other expression (TS2532, TS2533).

4The ! operator, and checked alternatives

The answer most often given for "suppress Object is possibly null" is the non-null assertion, a ! after an expression: scores.get("ada")! has type number instead of number | undefined. It is a promise to the compiler, not a check. It is deleted from the JavaScript output, so when the promise is wrong the program carries on with undefined until something breaks further along. When you need it often, a small helper that checks and throws gives the same type with a useful error: a function returning NonNullable<T>, or an assertion function that narrows the variable in place.

non-null.ts
const scores = new Map<string, number>([["ada", 92]]);

// ! removes null and undefined from the type; it is erased from the output
const adaScore: number = scores.get("ada")!;
console.log(adaScore + 1);

// Nothing checks it: when you are wrong, the value is still undefined
const bobScore: number = scores.get("bob")!;
console.log(bobScore, bobScore + 1);

interface Settings {
    theme?: { color: string };
}
const settings: Settings = {};
try {
    console.log(settings.theme!.color);
} catch (err) {
    console.log(err instanceof Error ? `${err.name}: ${err.message}` : err);
}

// A checked alternative: the same narrowed type, plus a clear error
function required<T>(value: T, what: string): NonNullable<T> {
    if (value == null) throw new Error(`${what} is missing`);
    return value;
}

const ada: number = required(scores.get("ada"), "score for ada");
console.log(ada);
try {
    const bob: number = required(scores.get("bob"), "score for bob");
    console.log(bob);
} catch (err) {
    console.log(err instanceof Error ? err.message : err);
}

// An assertion function narrows the variable itself
function assertDefined<T>(value: T, what: string): asserts value is NonNullable<T> {
    if (value == null) throw new Error(`${what} is missing`);
}
const theme = settings.theme;
try {
    assertDefined(theme, "theme");
    console.log(theme.color);
} catch (err) {
    console.log(err instanceof Error ? err.message : err);
}

Output

The correct assertion prints 93. The wrong one compiles just as happily and prints undefined NaN: a number variable holding undefined, and arithmetic quietly producing NaN. On an object it crashes, but at the property access, not at the !: TypeError: Cannot read properties of undefined (reading 'color'). The helpers fail where the value went missing and say what it was: required returns 92 and then throws score for bob is missing, and assertDefined throws theme is missing. Had it passed, theme.color would type-check with no !, because asserts value is NonNullable<T> narrows theme for the rest of the block. Use ! where a missing value really is impossible, such as right after your own map.set(key, …); turning strictNullChecks off to silence the errors switches off this whole page's worth of checking.

5Truthiness and typeof: checks that narrow too much or too little

TypeScript narrows on if (value) too, and removes null and undefined from the type, so the checker is satisfied. But the runtime check also sends 0, "", false and NaN down the "missing" branch, and the types don't warn you. The opposite trap is typeof: typeof null is "object", so typeof x === "object" leaves null in the type. For more on typeof, instanceof and type guards, see check a type at runtime.

traps.ts
// A truthiness check narrows out undefined, but it also catches 0
function itemsLabel(count: number | undefined): string {
    if (!count) return "no count";
    return `${count} items`;
}
function itemsLabelFixed(count: number | undefined): string {
    if (count === undefined) return "no count";
    return `${count} items`;
}
console.log(itemsLabel(0), "|", itemsLabelFixed(0), "|", itemsLabelFixed(undefined));

// The same with strings: "" is a value, but a truthiness check drops it
function heading(title: string | null): string {
    return title ? title : "(untitled)";
}
console.log(JSON.stringify(heading("")), JSON.stringify(heading(null)));

// typeof null is "object", so typeof alone does not rule out null
console.log(typeof null);

type Config = { port: number } | string | null;

function portOf(config: Config): number {
    if (typeof config === "object" && config !== null) {
        return config.port;
    }
    return -1;
}
console.log(portOf({ port: 8080 }), portOf("8080"), portOf(null));

Output

itemsLabel(0) prints no count although a count was passed; the === undefined version prints 0 items and keeps no count for the real undefined. The same happens to strings: heading("") and heading(null) both print "(untitled)", which is right only if an empty title should count as missing. typeof null prints object, and portOf prints 8080 -1 -1. Remove && config !== null and, with strict on, config.port fails with error TS18047: 'config' is possibly 'null'. Without strict it compiles, and portOf(null) crashes at runtime with TypeError: Cannot read properties of null (reading 'port').

6Which should you use?

ExpressionTreats as missingType afterwardsBest for
value == nullnull, undefinedNarrowed, both removedThe default check
value === undefinedundefined onlyNarrowed, undefined removedfind(), Map.get(), optional props
value ?? fallbacknull, undefinedBoth removedDefault values
value?.propnull, undefinedGains undefinedReading through optional objects
if (value)Also 0, "", false, NaNNarrowedOnly when 0 and "" mean missing
value!Nothing (no check)Both removed, uncheckedValues you know are there
required(value) / assertsnull, undefined (throws)NonNullable<T>When a missing value is a bug

Frequently asked questions

How do I fix "Object is possibly 'undefined'" in TypeScript?

Check the value before you use it, and TypeScript narrows the type: const product = products.find(f); if (product === undefined) return; product.name. Use ?. and ?? when you want a fallback instead of a branch (product?.name ?? "none"), or throw when a missing value is a bug. The message is TS2532 for an expression and TS18048 ('product' is possibly 'undefined') for a named variable. The ! operator (product!.name) silences it but checks nothing at runtime.

What does the exclamation mark after a variable mean in TypeScript?

It is the non-null assertion operator: value! tells the compiler that value is not null or undefined, so scores.get("ada")! has type number instead of number | undefined. It is removed from the compiled JavaScript and does no check, so if you are wrong the program runs on with undefined (here, undefined + 1 printed NaN). Prefer a real check, ??, or a helper that throws.

How do I fix "Type 'string | undefined' is not assignable to type 'string'"?

Decide what should happen when the value is missing. For a default, use ??: const nick: string = user.nickname ?? user.name. For a branch, check first: if (user.nickname !== undefined) { … }. If the target can be missing too, widen it to string | undefined or make the property optional. Avoid as string and !, which only hide the case.

Should I turn off strictNullChecks to get rid of these errors?

No. Without it, null and undefined are part of every type, so let s: string = null compiles and the crash moves to runtime. With strict or strictNullChecks on, that line fails with Type 'null' is not assignable to type 'string'. Every error it reports is a place where a missing value can reach code that does not expect one, and each fix is usually one check, one ?? or one ?..

What is the difference between name?: string and name: string | undefined?

Both read as string | undefined, but name?: string lets the property be left out, while name: string | undefined requires the key to be written, even as name: undefined. With the second, const b: B = {} fails with Property 'name' is missing in type '{}' but required in type 'B'. Use ?: for properties callers may omit.

How do I filter null and undefined out of an array with the right type?

Use arr.filter((x) => x != null). Since TypeScript 5.5 the checker infers that callback as a type guard, so [1, null, 2, undefined, 0] filters to number[] and prints [ 1, 2, 0 ]. arr.filter(Boolean) is not inferred that way (the result stays (number | null | undefined)[]), and at runtime it also drops 0: it printed [ 1, 2 ].

Run it yourself

Open any of these in the full TypeScript editor to tweak, run and share.

TypeScript playground