[Typescript] Extract & Exclude
amptypescript extract
2023-09-14 09:00:45 时间
Extract is useful for obtaining some sub-part of a type that is assignable to some other type.
type FavoriteColors =
| "dark sienna"
| "van dyke brown"
| "yellow ochre"
| "sap green"
| "titanium white"
| "phthalo green"
| "prussian blue"
| "cadium yellow"
| [number, number, number]
| { red: number; green: number; blue: number }
type StringColors = Extract<FavoriteColors, string> // "dark sienna" | "van dyke brown" | "yellow ochre" | "sap green" | "titanium white" | "phthalo green" | "prussian blue" | "cadium yellow"
type StringColorsEndsWithA = Extract<FavoriteColors, `${string}a`> // "dark sienna"
type ObjectColors = Extract<FavoriteColors, { red: number }> // { red: number; green: number; blue: number; }
type TupleColors = Extract<FavoriteColors, [number, number, number]> // [number, number, number]
type SingleNumberArray = Extract<FavoriteColors, [number]> // never
type AnyNumberArray = Extract<FavoriteColors, number[]> // [number, number, number]
Exclude
is the opposite of Extract
, in that it’s useful for obtaining the part of a type that’s not assignable to some other type
type FavoriteColors =
| "dark sienna"
| "van dyke brown"
| "yellow ochre"
| "sap green"
| "titanium white"
| "phthalo green"
| "prussian blue"
| "cadium yellow"
| [number, number, number]
| { red: number; green: number; blue: number }
type NonStringColors = Exclude<FavoriteColors, string>
/*
[number, number, number] | {
red: number;
green: number;
blue: number;
}
*/
Here’s the complete source code for these types:
/**
* Exclude from T those types that are assignable to U
*/
type Exclude<T, U> = T extends U ? never : T
/**
* Extract from T those types that are assignable to U
*/
type Extract<T, U> = T extends U ? T : never
相关文章
- js 反应&行动
- [Typescript] Get full type safe for discriminatedUnion type with 'type' & 'subtype' (2 levels)
- [Typescript] Step1 & 2 for converting a js app to ts
- [Typescript v4] Tuple Types && Recursive types
- Apache Spark技术实战(三)利用Spark将json文件导入Cassandra &SparkR的安装及使用
- [Typescript] Get full type safe for discriminatedUnion type with 'type' & 'subtype' (2 levels)
- [React Native] Up & Running with React Native & TypeScript
- [ES6] Array -- Destructuring and Rest Parameters && for ..of && Arrat.find()
- web渗透检测-跨站点脚本编制 & 链接注入 & 框架钓鱼(普及篇)
- 分布式服务 API 的幂等设计方案 & Spring Boot + Redis 拦截器实现实例
- 68:内网安全-域横向PTH&PTK&PTT哈希票据传递
- 【线代&NumPy】第八章 - 特征值和特征向量 | Eigenvalue and Eigenvector | 简述并提供代码