Check for empty type in typescript type mapping

488 Views Asked by At

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.

2

There are 2 best solutions below

0
captain-yossarian from Ukraine On BEST ANSWER

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

0
Jerome On

you can used never

type notEmpty<T extends Record<string, any>> = T extends Record<string, never> ? void : T;

type A= notEmpty<{}>  <-- A is void
type B = notEmpty<{test:"value"}> <-- B is {test:value}