typescript - 如何从其他类型中排除 {}?
问题描述
假设我有一个类型
type Z = {a: number} | {} | {b: boolean} | {c: string} | ...;
我怎样才能获得相同但没有{}
?
type Y = Exclude<Z, {}>;
⇧结果为Y = never
,因为所有变体都可以分配给{}
,所以被排除在外。
解决方案
您可以定义自己的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 }
推荐阅读
- delphi - 为什么我收到调用错误:找不到方法
- php - PHP:CURL 返回空数据
- android - 有什么方法可以让我们了解指纹认证的指纹细节吗?
- java - 如何在edittext android中取消加粗和取消突出显示选定的文本
- r - dplyr slice:有平局时基于向量的优先级
- angular - 将 ag-grid 与 flexbox 一起使用
- matlab - 协方差函数 - 内存不足
- php - 登录后我无法在 Yii 中重定向用户
- ruby-on-rails - 如何使用 Active Storage 和 mini_magick 屏蔽图像
- sql - 获取键/值结构字符串中的数字总和