I am seeking to create a custom mapped conditional type in TypeScript that will allow me to extract property names from a type, while accounting for properties that can potentially have a value of null
. For example:
interface Person {
name: string
age: number
category: string | null
}
type NotNullablePersonProps = NotNullablePropertyNames<Person>
// Expected output: "name" | "age"
I came across an example on GitHub that introduces the concepts of Optional and Required Property Names:
type OptionalPropertyNames<T> = {
[K in keyof T]-?: undefined extends T[K] ? K : never
}[keyof T];
type RequiredPropertyNames<T> = {
[K in keyof T]-?: undefined extends T[K] ? never : K
}[keyof T];
While this example is helpful, I struggled to modify it to account for properties with a value of null
.
How should I define a NotNullablePropertyNames
mapped conditional type to accurately return all property names that cannot be null
?