Extract not-nullable type definition from nullable type

Viewed 305

Let's say I have the following interface generated by an external tool:

interface Animals {
    turtle: { shellHardness: number };
    fox: { whatDidItSay: string } | null;
}

I would like to define (extract from Animals) a type for both the turtle and the fox but without the …| null for the fox. It is easy for the turtle because there is no null:

type Turtle = Animals["turtle"];

But how do I do it for the fox? I imagined there could be some ExtractNullable type that would remove the nullability:

type Fox = ExtractNullable<Animals, "fox">;

Unfortunately I was unable to define the ExtractNullable type properly. I tried the following:

type ExtractNullable<T, K extends keyof T> = T[K] extends null ? never : T[K];

…but it did not work. TypeScript playground still gives me that the Fox type is defined as type Fox = { whatTheySaid: string; } | null instead of type Fox = { whatTheySaid: string; }

Is this possible? What am I getting wrong?

Thank you

1 Answers

NonNullable<Type>

type Fox = NonNullable<Animals["fox"]>;

implementation:

/**
 * Exclude null and undefined from T
 */
type NonNullable<T> = T extends null | undefined ? never : T;
Related