lon*_*556 5 typescript typescript3.0
我有两种类型的联合,其中一种是空的 obj。
type U = {} | { a: number } // | { b: string } | { c: boolean } ....
Run Code Online (Sandbox Code Playgroud)
我想从联合中排除空对象但是Exclude没有帮助
type A = Exclude<U, {}>
// A = never
Run Code Online (Sandbox Code Playgroud)
我尝试使用,as const但结果相同
const empty = {} as const
type Empty = typeof empty
type U = Empty | { a: number }
type A = Exclude<U, Empty>
//type A = never
Run Code Online (Sandbox Code Playgroud)
额外的讽刺是,排除其他属性很简单
type B = Exclude<U, { a: number }>
// type B = {}
Run Code Online (Sandbox Code Playgroud)
那么是否可以从联合中的其他接口中排除空接口?
回答我自己的问题..
如果您使用AtLeastOne来自 @lukasgeiter 的答案:从 Partial 类型中排除空对象
您可以执行以下操作:
type AtLeastOne<T, U = {[K in keyof T]: Pick<T, K> }> = Partial<T> & U[keyof U];
type ExcludeEmpty<T> = T extends AtLeastOne<T> ? T : never;
type U = {} | { a: number } | { b: string }
type Foo = ExcludeEmpty<U> // { a: number } | { b: string }
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
165 次 |
| 最近记录: |