[Typescript] Extract & Exclude

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

 

相关文章

我最大的一个关于TypeScript的问题是,它将原型的所有方法(无...
我对React很新,我正在尝试理解子组件之间相互通信的简洁方法...
我有一个非常简单的表单,我将用户电子邮件存储在组件的状态,...
我发现接口非常有用,但由于内存问题我需要开始优化我的应用程...
我得到了一个json响应并将其存储在mongodb中,但是我不需要的...
我试图使用loadsh从以下数组中获取唯一类别,[{"listing...