• [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
  • 相关阅读:
    pip错误:'utf-8' codec can't decode byte解决方法
    windows中python2与python3共存
    Alpha 冲刺 (3/10)
    Alpha 冲刺 (2/10)
    Alpha 冲刺 (1/10)
    项目需求分析报告答辩总结
    项目选题报告答辩总结
    项目UML设计(团队)
    # 第七次作业--项目需求分析(团队)
    结对项目--第二次作业
  • 原文地址:https://www.cnblogs.com/Answer1215/p/16589338.html
Copyright © 2020-2023  润新知