Search code examples
typescripttype-mapping

Check for empty type in typescript type mapping


I want to check if a type is an empty object and if thats the case map that to the void type.

type notEmpty<T> = T extends {}
? void
: T;

The above code does not work because evyr object extends the empty object.
Another approach was to turn it around:

type notEmpty2<T> = T extends { any: any }
    ? void
    : T;

But that would match only the object with the property any not any property.


Solution

  • You can also check whether T has some keys:

    type IsEmpty<T extends Record<PropertyKey, any>> =
      keyof T extends never
      ? true
      : false
    
    type _ = IsEmpty<{}> // true
    type __ = IsEmpty<{ a: number }> // false
    type ___ = IsEmpty<{ a: never }> // false
    

    Playground