typescript - 打字稿从类型中排除类型
问题描述
interface First {
field1: number;
}
interface Second {
field2: number
}
interface Third extends First, Second {
}
// type Forth = Omit<Third, Second>
// expect Fourth to be { field1: number}
使用众所周知的省略类型,我们可以省略类型中的属性
type Omit<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>
例如
Omit<Third, 'field2'> and it will work as the above
但问题是当 Second 有多个字段时
这是可以实现的吗?如何?
解决方案
如果要从另一种类型中排除一种类型的所有键,可以将keyof
其用作参数Omit
:
type Omit<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>
interface First {
field1: number;
}
interface Second {
field2: number
}
interface Third extends First, Second {
}
type ThirdWithoutSecond = Omit<Third, keyof Second>
推荐阅读
- c - c - 更新定义为 char 指针变量的字符串
- c++ - C++ 中是否存在将 {1,2,2} 和 {2,1,2} 视为相等的结构/容器?
- c - 取消引用的未初始化指针在内存中的位置?
- android - startForegroundService - 指定自定义“后台应用程序正在运行..”通知?
- html - 如何更改 helpText R Shiny 的颜色
- c# - 将会话请求添加到 API 调用
- python - 根据单列对 pandas 中的多列进行排序
- c++ - 为什么在`int`和`long long int`之间不能使用`std::min`
- python-3.x - Python 多处理池突然停止
- r - R如何在向量中找到一系列共同值(识别生长季节)