Skip to content

Instantly share code, notes, and snippets.

@adriangabardo
Created April 12, 2022 06:27
Show Gist options
  • Save adriangabardo/950076d57a5fc4e29611cf47c2a61af7 to your computer and use it in GitHub Desktop.
Save adriangabardo/950076d57a5fc4e29611cf47c2a61af7 to your computer and use it in GitHub Desktop.
Example of a generic type alias that transforms a given type into a nullable type (including sub-properties in case of objects)
/**
* Type alias to recursively make all properties of an object optionally undefined or null.
* Adds | undefined | null to all objects and its properties.
*/
type DeepNullable<T> = T extends object
? { [k in keyof T]?: DeepNullable<T[k] | null> }
: T | null;
interface TestObj {
nothing: boolean;
is: number;
nullish: string;
not: {
even: {
objects: boolean;
};
right: string;
};
}
const testObj: TestObj = {
nothing: true,
is: 1,
nullish: "yeah",
not: {
even: {
objects: true
},
right: "yeah"
}
};
const testNullable: DeepNullable<TestObj> = {};
@adriangabardo
Copy link
Author

Extra contraction:

type NulledT<T> = T | Null;

type DeepNullable<T> = T extends object
  ? { [k in keyof T]?: DeepNullable<NulledT<T[k]>> }
  : NulledT<T>;

Not more readable, just more concise

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment