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.
CodePudding user response:
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
CodePudding user response:
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}
