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