Search code examples
typescriptmapped-typesconditional-types

In TypeScript how might one create a mapped, conditional type that removes properties of type string | null


Here's my final failed attempt before coming here for advice. What am I doing wrong pls ty?

interface Something {
  id: string;
  name: string | null;
}

interface AnotherThing {
  id: string;
  name: string;
}

type ExcludeNullableFields<A> = {
  [K in keyof A as A[K] extends string | null ? K : never]: A[K] ;
};

type NamelessThing = ExcludeNullableFields<Something>; 
// desired outcome: { id: string }

type NamedThing = ExcludeNullableFields<AnotherThing>; 
// desired outcome: { id: string; name: string }

Solution

  • If you tweak ExcludeNullableFields to this..

    type ExcludeNullableFields<A> = {
      [K in keyof A as Extract<A[K], null> extends  never ? K : never]: A[K] ;
    };
    

    Basically I'm checking to see if I can extract null from any of the types. If a type doesn't contain null, then extract will return never. But if Extract does find the type null then I know a field is nullable.