HiveBrain v1.2.0
Get Started
← Back to all entries
patterntypescriptMajor

remove null or undefined from properties of a type

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
frompropertiesremoveundefinedtypenull

Problem

I need to declare a type such that removes the undefined from its property types.

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:

type NoUndefinedField = { [P in keyof T]-?: NoUndefinedField> };


Notice the -? syntax in [P in keyof T]-? which removes optionality

Code Snippets

type NoUndefinedField<T> = { [P in keyof T]-?: NoUndefinedField<NonNullable<T[P]>> };

Context

Stack Overflow Q#53050011, score: 87

Revisions (0)

No revisions yet.