Created
April 12, 2022 06:27
-
-
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)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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> = {}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Extra contraction:
Not more readable, just more concise