patterntypescriptMajor
remove null or undefined from properties of a type
Viewed 0 times
frompropertiesremoveundefinedtypenull
Problem
I need to declare a type such that removes the undefined from its property types.
Suppose we have:
I need to define a generic type called
I tried this
But it only works for
Suppose we have:
type Type1{
prop?: number;
}
type Type2{
prop: number | undefined;
}
type Type3{
prop: number;
}I need to define a generic type called
NoUndefinedField such that NoUndefinedField gives the same type as Type3 and the same type as NoUndefinedField.I tried this
type NoUndefinedField = { [P in keyof T]: Exclude };But it only works for
Type2.Solution
Thanks to @artem, the solution is:
Notice the
type NoUndefinedField = { [P in keyof T]-?: NoUndefinedField> };Notice the
-? syntax in [P in keyof T]-? which removes optionalityCode Snippets
type NoUndefinedField<T> = { [P in keyof T]-?: NoUndefinedField<NonNullable<T[P]>> };Context
Stack Overflow Q#53050011, score: 87
Revisions (0)
No revisions yet.