Excluding null
and undefined
from object properties with TypeScript
#TypeScript
Here's a simple TypeScript code snippet that helps determine the type of an object while excluding null and undefined from all possible values of its properties.
type NonNullableProperties<T> = {
[P in keyof T]: NonNullable<T[P]>;
};
What's going on here?
keyof T
- using thekeyof
operator to get the union of all keys ofT
.NonNullable<T[P]>
- here we're utilizing theNonNullable
utility type to excludenull
andundefined
from the typeT[P]
. This does not apply to optional properties. For those, you can use the-?
syntax in theNonNullableProperties
type, as shown below."[P in keyof T]: NonNullable<T[P]>
is a mapped type that iterates over all the properties ofT
and replaces their types withNonNullable<T[P]>
.
Here's an example of how to use it:
type ExampleType = {
a?: string | null;
b?: number | undefined;
c: boolean | undefined | null;
d: string;
};
type NonNullableExampleType = NonNullableProperties<ExampleType>;
// 👇
// { a?: string; b?: number; c: boolean; d: string }
If you want to remove optionaly properties from the type, you can use the Required
utility type:
type RequiredExampleType = Required<ExampleType>;
// 👇
// { a: string; b: number; c: boolean; d: string }
or using -?
syntax in NonNullableProperties
:
type NonNullableProperties<T> = {
[P in keyof T]-?: NonNullable<T[P]>;
};
type NonNullableExampleType = NonNullableProperties<ExampleType>;