检查打字稿类型映射中的空类型

Check for empty type in typescript type mapping

我想检查一个类型是否为空对象,如果是,则将其映射到 void 类型。

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

以上代码不起作用,因为 evyr 对象扩展了空对象。
另一种方法是扭转局面:

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

但这只会匹配具有 属性 any 的对象,而不匹配任何 属性.

你可以使用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}

您还可以检查T是否有一些键:

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