The accepted answer is actually not answering the question since it was asked for a generic way.

Here is one that is similar and will also cast the return type properly:

type RecursivelyReplaceNullWithUndefined<T> = T extends null
  ? undefined
  : T extends Date
  ? T
  : {
      [K in keyof T]: T[K] extends (infer U)[]
        ? RecursivelyReplaceNullWithUndefined<U>[]
        : RecursivelyReplaceNullWithUndefined<T[K]>;
    };

export function nullsToUndefined<T>(obj: T): RecursivelyReplaceNullWithUndefined<T> {
  if (obj === null) {
    return undefined as any;
  }

  // object check based on: https://stackoverflow.com/a/51458052/6489012
  if (obj.constructor.name === "Object") {
    for (let key in obj) {
      obj[key] = nullsToUndefined(obj[key]) as any;
    }
  }
  return obj as any;
}

Credits go to the typings of this genius: https://github.com/apollographql/apollo-client/issues/2412#issuecomment-755449680

Answer from ysfaran on Stack Overflow
Top answer
1 of 9
21

The accepted answer is actually not answering the question since it was asked for a generic way.

Here is one that is similar and will also cast the return type properly:

type RecursivelyReplaceNullWithUndefined<T> = T extends null
  ? undefined
  : T extends Date
  ? T
  : {
      [K in keyof T]: T[K] extends (infer U)[]
        ? RecursivelyReplaceNullWithUndefined<U>[]
        : RecursivelyReplaceNullWithUndefined<T[K]>;
    };

export function nullsToUndefined<T>(obj: T): RecursivelyReplaceNullWithUndefined<T> {
  if (obj === null) {
    return undefined as any;
  }

  // object check based on: https://stackoverflow.com/a/51458052/6489012
  if (obj.constructor.name === "Object") {
    for (let key in obj) {
      obj[key] = nullsToUndefined(obj[key]) as any;
    }
  }
  return obj as any;
}

Credits go to the typings of this genius: https://github.com/apollographql/apollo-client/issues/2412#issuecomment-755449680

2 of 9
9

The accepted answer is not type safe.

This answer is close, but doesn't handle null inside of nested arrays.

This will replace null with undefined in nested objects and arrays:

type RecursivelyReplaceNullWithUndefined<T> = T extends null
  ? undefined
  : T extends (infer U)[]
  ? RecursivelyReplaceNullWithUndefined<U>[]
  : T extends Record<string, unknown>
  ? { [K in keyof T]: RecursivelyReplaceNullWithUndefined<T[K]> }
  : T;

export function nullsToUndefined<T>(
  obj: T,
): RecursivelyReplaceNullWithUndefined<T> {
  if (obj === null || obj === undefined) {
    return undefined as any;
  }

  if ((obj as any).constructor.name === 'Object' || Array.isArray(obj)) {
    for (const key in obj) {
      obj[key] = nullsToUndefined(obj[key]) as any;
    }
  }
  return obj as any;
}
🌐
Reddit
reddit.com › r/typescript › replacing "null" with "undefined"
r/typescript on Reddit: Replacing "null" with "undefined"
January 6, 2023 -

I want to create a type that loops through an object and replaces all nulls with undefined. For example:

// input:
// {
//   a: string | null;
//   b: string;
// }

// returns:
// {
//   a: string | undefined;
//   b: string;
// }

The best I Have so far is this

export type ReplaceNullWithUndefined<T extends Object> = {
  [key in keyof T]: Extract<T[key], null> extends null
    ? Exclude<T[key], null> | undefined
    : T[key];
}; 

// which with input:
// {
//   a: string | null;
//   b: string;
// }

// returns:
// {
//   a: string | undefined;
//   b: string | undefined;
// }

Thank you, any help would be amazing

🌐
GitHub
github.com › apollographql › apollo-client › issues › 2412
converting `null` to `undefined` · Issue #2412 · apollographql/apollo-client
October 28, 2017 - const httpLink = createHttpLink({ uri: window.xnGlobals.ENDPOINT_GQL, fetch, }) const nullToUndefined = value => { if (isPlainObject(value)) { return mapValues(value, nullToUndefined) } if (isArray(value)) { return value.map(nullToUndefined) } if (value === null) { return undefined // THIS SHOULD BE UNDEFINED } return value } const nullLink = new ApolloLink((operation, forward) => forward(operation).map(nullToUndefined)) const link = nullLink.concat(httpLink)
Published   Oct 28, 2017
🌐
W3Schools
w3schools.com › typescript › typescript_null.php
TypeScript Null & Undefined
By default null and undefined handling is disabled, and can be enabled by setting strictNullChecks to true. 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.
🌐
Sdorra
sdorra.dev › posts › 2023-03-20-typescript-undefined-to-null
TypeScript undefined to null | sdorra.dev
March 21, 2024 - Learn how to create a type helper which converts undefined to null
🌐
npm
npmjs.com › package › null-as-undefined
null-as-undefined
Convert null values to undefined in a way that TypeScript understands.
      » npm install null-as-undefined
    
Published   Oct 24, 2021
Version   0.4.0
🌐
Tektutorialshub
tektutorialshub.com › home › typescript › null vs undefined in typescript
Null Vs Undefined in TypeScript - Tektutorialshub
March 15, 2023 - You can use typeof operator to check for undefined but not null as it returns “object”. You can use the == & === operator to check their values · Checking for null. Comparing null with undefined results in different results depending on whether you use an equality checker (==) or strict equality checker (===) null and undefined both represents no value hence equality checker (==) returns true. This is because the equality checker does not check for data type · But strict equality checker returns false because it also checks for the data type. Converting undefined to Number will result in NaN.
Find elsewhere
🌐
Lightrun
lightrun.com › answers › apollographql-apollo-tooling-generate-undefined-instead-of-null-in-typescript
Generate undefined instead of null in typescript
Can we have an option argument to generate undefined instead of null in typescript? Coming from swift world, it will be pretty useful to just deal with undefined than adding null to the mix. ... As such, it’s frustrating to try to interoperate generated models with nullable types into a codebase that uses undefined everywhere. Imagine a simple React component whose props look as follows: ... I would not be able to pass apolloGeneratedModel.name into this component without first converting null to undefined – an unnecessary step in a codebase that has already decided that the distinction between null and undefined is not adding value, and that undefined is to be used in all cases as such.
🌐
GitBook
basarat.gitbook.io › typescript › recap › null-undefined
Null vs. Undefined | TypeScript Deep Dive
Since attributes set to null are encoded, you can transmit the intent to clear an attribute by setting its value to null before encoding and transmitting the object to a remote store. Setting attribute values to undefined can save on storage and transmission costs, as the attribute names will not be encoded. However, this can complicate the semantics of clearing values vs. absent values. TypeScript team doesn't use null : TypeScript coding guidelines and it hasn't caused any problems.
🌐
Webdevtutor
webdevtutor.net › blog › typescript-null-to-undefined
Converting Null to Undefined in TypeScript: A Comprehensive Guide
By explicitly specifying the type as undefined, you can safely convert null values to undefined.
🌐
Reddit
reddit.com › r/typescript › undefined vs null
r/typescript on Reddit: Undefined vs null
February 27, 2023 -

Since switching to TypeScript I have been using a lot of optional properties, for example:

type store = {
  currentUserId?: string
}

function logout () {
  store.currentUserId = undefined
}

However my coworkers and I have been discussing whether null is a more appropriate type instead of undefined, like this:

type store = {
  currentUserId: string | null
}

function logout () {
  store.currentUserId = null
}

It seems like the use of undefined in TypeScript differs slightly from in Javascript.

Do you guys/girls use undefined or null more often? And, which of the examples above do you think is better?

🌐
TypeScript
typescriptlang.org › docs › handbook › release-notes › typescript-2-0.html
TypeScript: Documentation - TypeScript 2.0
TypeScript has two special types, Null and Undefined, that have the values null and undefined respectively. Previously it was not possible to explicitly name these types, but null and undefined may now be used as type names regardless of type checking mode.
🌐
Bobby Hadz
bobbyhadz.com › blog › javascript-convert-null-to-zero
Convert NULL/Undefined/NaN to 0 using JavaScript | bobbyhadz
Use the logical nullish assignment operator to convert `null` or `undefined` to `0`, e.g. `val ??= 0;`.
🌐
Webdevtutor
webdevtutor.net › blog › typescript-cast-null-to-undefined
How to Cast Null to Undefined in TypeScript
One common approach to cast null to undefined in TypeScript is through type assertion. By explicitly specifying the type of a variable, you can effectively convert null to undefined.
🌐
Omarileon
omarileon.me › blog › typescript-null-undefined
mari. | How to Detect Null and Undefined in Your TypeScript Code
February 27, 2024 - Another way to check for null or undefined is to use the nullish coalescing operator (??), which was introduced in TypeScript 3.7. If the left-hand side of the operation is non-null it returns that, otherwise it returns the right-hand side otherwise.
🌐
Webmaster World
webmasterworld.com › javascript › 5090854.htm
Easy way to convert undefined to false? - JavaScript and AJAX forum at WebmasterWorld - WebmasterWorld
That said, typeof x === 'undefined' So (y = typeof(x === 'undefined' ? false : true) ... EDIT: I'm really struggling with the code editor on Webmaster World. It's removing one of the exclamation points, so where you see DBL! in the code below, that's meant to represent two !. [mods note: fixed the double ! problem] There are a couple of ways, but my favorite is with a double NOT operator. The NOT operator (!) will implicitly convert values to a boolean, with the value being the negated version.
🌐
GeeksforGeeks
geeksforgeeks.org › typescript › how-to-check-null-and-undefined-in-typescript
How to check null and undefined in TypeScript ? - GeeksforGeeks
July 23, 2025 - In this approach, we utilize the optional chaining (?.) and nullish coalescing (??) operators to check if a variable is null or undefined. These operators provide a concise and readable way to handle null and undefined values in TypeScript.