Remove null and undefined from type (including nested props)

Viewed 52

I found this resource, which works great for types that don't have nested props. https://bobbyhadz.com/blog/typescript-remove-null-and-undefined-from-type

But in my case, I need to strip all props, even nested ones.

Is there any solution for doing that?

Note. My types are automatically generated in hundreds, so manually doing it is not an option.

Example type:

type BlogSlugQuery = {
    __typename?: "Query" | undefined;
    Blogs?: {
        __typename?: "Blogs" | undefined;
        docs?: ({
            __typename?: "Blog" | undefined;
            slug?: string | null | undefined;
        } | null)[] | null | undefined;
    } | null | undefined;
}
1 Answers

This seems to be working:

type WithoutNullableKeys<Type> = {
  [Key in keyof Type]-?: Type[Key] extends (object | undefined | null) 
     ? WithoutNullableKeys<Type[Key]> 
     : NonNullable<Type[Key]>;
};

Although the type expression shown like this:

type T2 = {
    __typename: "Query";
    Blogs: WithoutNullableKeys<{
        __typename?: "Blogs" | undefined;
        docs?: ({
            __typename?: "Blog" | undefined;
            slug?: string | null | undefined;
        } | null)[] | null | undefined;
    }> | null;
}

... so that recursion is not taken down the line, it seems to correctly warn on omitting the properties and/or setting them up to null/undefined:

enter image description here

TS Playground.

Related