Imagine having a type like this:
type Properties = {
name: string
age?: number
city?: string
}
If you only want to create a type with age
and city
as required fields, you can do it like this:
type RequiredFields = RequiredOptional<Properties>
This will give you:
type RequiredFields = {
age: number
city: string
}
Is this achievable and how?
I have come across solutions (such as this) on extracting optional keys from a type, but not exactly what I am looking for. The closest I've got is:
type OptionalKeysOfType<T extends object> = keyof {
[K in keyof T as T extends Record<K, T[K]> ? never : K]: K
}
type RequiredFields = {
[key in OptionalKeysOfType<Properties>]: NonNullable<Properties[key]>
}
However, this method has two issues:
- It's not very generic
- The displayed keys in VSCode/NVim appear as
instead of(property) timeout: NonNullable<number | boolean | undefined>
(property) timeout: number | boolean