首页 > 解决方案 > 如何从其他类型中排除 {}?

问题描述

假设我有一个类型

type Z = {a: number} | {} | {b: boolean} | {c: string} | ...;

我怎样才能获得相同但没有{}

type Y = Exclude<Z, {}>;

⇧结果为Y = never,因为所有变体都可以分配{},所以被排除在外。

标签: typescript

解决方案


您可以定义自己的Exclude-like 类型函数,例如ExcludeSupertypes<T, U>将其拆分T为联合成员并排除任何此类成员,这些成员是 的超类型U不是 的子类型U

type ExcludeSupertypes<T, U> = T extends any ? U extends T ? never : T : never;

这可以按您的意愿工作Z

type Y = ExcludeSupertypes<Z, {}>
// type Y = { a: number } | { b: boolean } | { c: string }

Playground 代码链接


推荐阅读