是否可以从联合中排除空对象?

时间:2020-04-24 14:04:33

标签: typescript typescript3.0

我有两种类型的并集,其中一种是空的obj。

type U = {} | { a: number } // | { b: string } | { c: boolean } ....

我想从联合中排除空对象,但是Exclude没有帮助

type A = Exclude<U, {}>
// A = never

我尝试使用as const,但结果相同

const empty = {} as const
type Empty = typeof empty
type U = Empty | { a: number }
type A = Exclude<U, Empty>
//type A = never

具有讽刺意味的是,排除其他属性很简单

  type B = Exclude<U, { a: number }>
  // type B = {}

TS Playground

那么有可能在联合中的其他接口中排除空接口吗?

2 个答案:

答案 0 :(得分:1)

从用于条件键入here的文档中,您实际上可以根据某些条件分配类型。

T extends U ? X : Y

因此对于上述问题,您可以做的是利用keyof关键字,该关键字用于从对象中提取键。如果找不到任何键,则类型永远不会如此,我们可以检查keyof object是否从不扩展,即

 keyof K extends never

因此在下面梳理条件类型;

const empty = {} as const
type Empty = typeof empty

type NoEmpty<K> = keyof K extends never ? never : K;

type C = NoEmpty<Empty>;

type U = NoEmpty<Empty> | NoEmpty<{ a: number }>

您最终可以看到U的类型是非空对象,即排除空对象。选中此playground

答案 1 :(得分:1)

回答我自己的问题。

如果您使用@lukasgeiter中的val obj = object: Runnable{ override fun run() { for (i in 1..3) { println("$i") Thread.sleep(500) } } } ,请在这里回答:Exclude empty object from Partial type

您可以执行以下操作:

AtLeastOne

TSplayground