• TypeScripe 笔记: 类型工具总结


    TypeScripe 笔记: 内置类型工具总结

    jcLee95 的CSDN博客
    本文地址https://blog.csdn.net/qq_28550263/article/details/128169632

    目 录

    1. 类型构造工具

    2. 字符串操作类型工具


    1. 类型构造工具

    类型工具描述
    Awaited这种类型旨在对 async 函数中的 awaitPromises-specific 上的 .then() 方法等操作进行建模,特别是——它们以递归方式展开 promises
    Partial构造一个 type 的所有属性都设置为可选的类型。该实用程序将返回一个表示给定类型的所有子集的类型。
    Required构造由设置为 required 的所有类型属性组成的类型。Partial 的逆操作。
    Readonly构造一个所有类型属性都设置为 readonly 的类型,这意味着不能重新分配构造类型的属性。
    Record构造一个对象类型,其属性键是Keys,属性值是Type。该实用工具可用于将一种类型的属性映射到另一种类型。
    Pick通过从类型中选取一组属性Keys(字符串或字符串的联合)来构造类型。
    Omit通过从类型中选取所有属性,然后移除Keys(字符串文字或字符串文字的联合)来构造类型。
    Exclude通过从UnionType中排除所有可分配给ExcludedMembers的联合成员来构造类型。
    Extract通过从Type中提取可分配给 Union 的所有联合成员来构造类型。
    NonNullable通过从 Type 中排除 nullundefined 来构造类型。
    Parameters从函数类型 Type 的参数中使用的类型构造元组类型。
    ConstructorParameters从构造函数类型的类型构造元组或数组类型。它产生一个包含所有参数类型的 tuple 类型(如果类型不是函数,则为 never 类型)。
    ReturnType构造由函数类型的返回类型组成的类型。
    InstanceType构造由类型中构造函数的实例类型组成的类型。
    ThisParameterType提取函数类型的 this 参数的类型,如果函数类型没有 this 参数,则为 unknown
    OmitThisParameter从 Type 中移除此参数。如果 Type 没有显式声明此参数,则结果只是 Type。否则,将从 Type 创建一个不带此参数的新函数类型。泛型被删除,只有最后一个重载签名被传播到新的函数类型中。
    ThisType该实用工具不返回转换后的类型。相反,它充当上下文 this 类型的标记。请注意,要使用此实用程序,必须启用 noImplicitThis 标志。

    1.1 Awaited

    这种类型旨在对 async 函数中的 awaitPromises-specific 上的 .then() 方法等操作进行建模,特别是——它们以递归方式展开 promises

    type A = Awaited<Promise<string>>;            // type A = string
    type B = Awaited<Promise<Promise<number>>>;   // type B = number
    type C = Awaited<boolean | Promise<number>>;  // type C = number | boolean
    
    • 1
    • 2
    • 3

    1.2 Partial

    构造一个 type 的所有属性都设置为可选的类型。该实用程序将返回一个表示给定类型的所有子集的类型。

    interface Todo {
      title: string;
      description: string;
    }
     
    function updateTodo(todo: Todo, fieldsToUpdate: Partial<Todo>) {
      return { ...todo, ...fieldsToUpdate };
    }
     
    const todo1 = {
      title: "organize desk",
      description: "clear clutter",
    };
     
    const todo2 = updateTodo(todo1, {
      description: "throw out trash",
    });
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

    1.3 Required

    构造由设置为 required 的所有类型属性组成的类型。Partial 的逆操作。

    interface Props {
      a?: number;
      b?: string;
    }
    const obj: Props = { a: 5 };
    
    // 错误:类型 `{ a: number; }` 中缺少属性 `b`,但在类型 `Required` 中是必需的。
    const obj2: Required<Props> = { a: 5 }; 
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    1.4 Readonly

    构造一个所有类型属性都设置为 readonly 的类型,这意味着不能重新分配构造类型的属性。

    interface Todo {
      title: string;
    }
    const todo: Readonly<Todo> = {
      title: "Delete inactive users",
    };
    
    // 错误:无法分配给 `title`,因为它是只读属性。
    todo.title = "Hello";  
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    该工具对于表示将在运行时失败的赋值表达式非常有用(例如,当尝试重新分配冻结对象的属性时)。

    1.5 Record

    构造一个对象类型,其属性键是Keys,属性值是Type。该实用工具可用于将一种类型的属性映射到另一种类型。

    interface CatInfo {
      age: number;
      breed: string;
    }
     
    type CatName = "miffy" | "boris" | "mordred";
     
    const cats: Record<CatName, CatInfo> = {
      miffy: { age: 10, breed: "Persian" },
      boris: { age: 5, breed: "Maine Coon" },
      mordred: { age: 16, breed: "British Shorthair" },
    };
    
    // const cats: Record
    cats.boris;
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    1.6 Pick

    通过从类型中选取一组属性Keys(字符串或字符串的联合)来构造类型。

    interface Todo {
      title: string;
      description: string;
      completed: boolean;
    }
     
    type TodoPreview = Pick<Todo, "title" | "completed">;
     
    const todo: TodoPreview = {
      title: "Clean room",
      completed: false,
    };
    
    // const todo: TodoPreview
    todo;
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    1.7 Omit

    通过从类型中选取所有属性,然后移除Keys(字符串文字或字符串文字的联合)来构造类型。

    interface Todo {
      title: string;
      description: string;
      completed: boolean;
      createdAt: number;
    }
     
    type TodoPreview = Omit<Todo, "description">;
     
    const todo: TodoPreview = {
      title: "Clean room",
      completed: false,
      createdAt: 1615544252770,
    };
    
    // const todo: TodoPreview
    todo;
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    type TodoInfo = Omit<Todo, "completed" | "createdAt">;
     
    const todoInfo: TodoInfo = {
      title: "Pick up kids",
      description: "Kindergarten closes at 5pm",
    };
    
    
    // const todoInfo: TodoInfo
    todoInfo;
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    1.8 Exclude

    通过从UnionType中排除所有可分配给ExcludedMembers的联合成员来构造类型。

    type T0 = Exclude<"a" | "b" | "c", "a">;                     // type T0 = "b" | "c"
    type T1 = Exclude<"a" | "b" | "c", "a" | "b">;               // type T1 = "c"
    type T2 = Exclude<string | number | (() => void), Function>; // type T2 = string | number
    
    • 1
    • 2
    • 3

    1.9 Extract

    通过从Type中提取可分配给 Union 的所有联合成员来构造类型。

    type T0 = Extract<"a" | "b" | "c", "a" | "f">;                // type T0 = "a"
    type T1 = Extract<string | number | (() => void), Function>;  // type T1 = () => void
    
    • 1
    • 2

    1.10 NonNullable

    通过从 Type 中排除 nullundefined 来构造类型。

    type T0 = NonNullable<string | number | undefined>;  // type T0 = string | number
    type T1 = NonNullable<string[] | null | undefined>;  // type T1 = string[]
    
    • 1
    • 2

    1.11 Parameters

    从函数类型 Type 的参数中使用的类型构造元组类型。

    declare function f1(arg: { a: number; b: string }): void;
     
    type T0 = Parameters<() => string>;        // type T0 = []
    type T1 = Parameters<(s: string) => void>; // type T1 = [s: string]
    type T2 = Parameters<<T>(arg: T) => T>;    // type T2 = [arg: unknown]
    type T3 = Parameters<typeof f1>;           // type T3 = [arg: { a: number; b: string;}]
    type T4 = Parameters<any>;                 // type T4 = unknown[]
    type T5 = Parameters<never>;               // type T5 = never
    
    // 类型 `string` 不满足约束`(...args: any) => any`。
    type T6 = Parameters<string>;              // type T6 = never
    
    // 类型 `Function` 不满足约束 `(...args: any) => any`。
    // 类型 `Function` 没有为签名 `(...args: any): any`。
    type T7 = Parameters<Function>;            // type T7 = never
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    1.12 ConstructorParameters

    从构造函数类型的类型构造元组或数组类型。它产生一个包含所有参数类型的 tuple 类型(如果类型不是函数,则为 never 类型)。

    type T0 = ConstructorParameters<ErrorConstructor>;     // type T0 = [message?: string]
    type T1 = ConstructorParameters<FunctionConstructor>;  // type T1 = string[]
    type T2 = ConstructorParameters<RegExpConstructor>;    // type T2 = [pattern: string | RegExp, flags?: string]
    type T3 = ConstructorParameters<any>;                  // type T3 = unknown[]
    
    // 类型 'Function' 不满足约束 `abstract new (...args: any) => any`.
    // 类型 'Function' 没有为签名提供匹配项 `new (...args: any): any`.
    type T4 = ConstructorParameters<Function>;             // type T4 = never
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    1.13 ReturnType

    构造由函数类型的返回类型组成的类型。

    declare function f1(): { a: number; b: string };
     
    type T0 = ReturnType<() => string>;        // type T0 = string
    type T1 = ReturnType<(s: string) => void>; // type T1 = void
    type T2 = ReturnType<<T>() => T>;          // type T2 = unknown
    type T3 = ReturnType<<T extends U, U extends number[]>() => T>;  // type T3 = number[]
    type T4 = ReturnType<typeof f1>;           // type T4 = { a: number; b: string;}
    type T5 = ReturnType<any>;                 // type T5 = any
    type T6 = ReturnType<never>;               // type T6 = never
    
    // 类型 `string` does not satisfy the constraint '(...args: any) => any'.
    type T7 = ReturnType<string>;              // type T7 = any
    
    // 类型 `Function` 不满足约束 `(...args: any) => any`.
    // 类型 `Function` 没有为签名提供匹配项 `(...args: any): any`.
    type T8 = ReturnType<Function>;            // type T8 = any
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16

    1.14 InstanceType

    构造由类型中构造函数的实例类型组成的类型。

    class C {
      x = 0;
      y = 0;
    }
     
    type T0 = InstanceType<typeof C>;  // type T0 = C
    type T1 = InstanceType<any>;       // type T1 = any
    type T2 = InstanceType<never>;     // type T2 = never
    
    // 类型 `string` 不满足约束 `abstract new (...args: any) => any`.
    type T3 = InstanceType<string>;    // type T3 = any
    
    // 类型 `Function` 不满足约束 `abstract new (...args: any) => any`.
    // 类型 `Function` 没有为签名提供匹配项 `new (...args: any): any`.
    type T4 = InstanceType<Function>;  // type T4 = any
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    1.15 ThisParameterType

    提取函数类型的 this 参数的类型,如果函数类型没有 this 参数,则为 unknown

    function toHex(this: Number) {
      return this.toString(16);
    }
     
    function numberToString(n: ThisParameterType<typeof toHex>) {
      return toHex.apply(n);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    1.16 OmitThisParameter

    从 Type 中移除此参数。如果 Type 没有显式声明此参数,则结果只是 Type。否则,将从 Type 创建一个不带此参数的新函数类型。泛型被删除,只有最后一个重载签名被传播到新的函数类型中。

    function toHex(this: Number) {
      return this.toString(16);
    }
     
    const fiveToHex: OmitThisParameter<typeof toHex> = toHex.bind(5);
     
    console.log(fiveToHex());
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    1.17 ThisType

    该实用工具不返回转换后的类型。相反,它充当上下文 this 类型的标记。

    注意,要使用此实用程序,必须启用 noImplicitThis 标志。

    type ObjectDescriptor<D, M> = {
      data?: D;
      methods?: M & ThisType<D & M>; // 方法中 `this` 的类型是 D & M
    };
     
    function makeObject<D, M>(desc: ObjectDescriptor<D, M>): D & M {
      let data: object = desc.data || {};
      let methods: object = desc.methods || {};
      return { ...data, ...methods } as D & M;
    }
     
    let obj = makeObject({
      data: { x: 0, y: 0 },
      methods: {
        moveBy(dx: number, dy: number) {
          this.x += dx; // 强类型化 this
          this.y += dy; // 强类型化 this
        },
      },
    });
     
    obj.x = 10;
    obj.y = 20;
    obj.moveBy(5, 5);
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24

    2. 字符串操作类型工具

    为了有助于字符串操作,TypeScript包含了一组可用于字符串操作的类型。这些类型内置于编译器中以提高性能,在TypeScript 附带的. d.ts文件中找不到。

    类型工具描述
    Uppercase将字符串中的每个字符转换为大写形式。
    Lowercase将字符串中的每个字符转换为小写形式。
    Capitalize将字符串中的第一个字符转换为等效的大写字符。
    Uncapitalize将字符串中的第一个字符转换为小写的等效字符。

    2.1 Uppercase

    将字符串中的每个字符转换为大写形式。

    type Greeting = "Hello, world";
    type ShoutyGreeting = Uppercase<Greeting>;  // type ShoutyGreeting = "HELLO, WORLD"
     
    type ASCIICacheKey<Str extends string> = `ID-${Uppercase<Str>}`;
    type MainID = ASCIICacheKey<"my_app">;      // type MainID = "ID-MY_APP"
    
    • 1
    • 2
    • 3
    • 4
    • 5

    2.2 Lowercase

    将字符串中的每个字符转换为小写形式。

    type Greeting = "Hello, world";
    type QuietGreeting = Lowercase<Greeting>;  // type QuietGreeting = "hello, world"
     
    type ASCIICacheKey<Str extends string> = `id-${Lowercase<Str>}`;
    type MainID = ASCIICacheKey<"MY_APP">;     // type MainID = "id-my_app"
    
    • 1
    • 2
    • 3
    • 4
    • 5

    2.3 Capitalize

    将字符串中的第一个字符转换为等效的大写字符。

    type LowercaseGreeting = "hello, world";
    type Greeting = Capitalize<LowercaseGreeting>;  // type Greeting = "Hello, world"
    
    • 1
    • 2

    2.4 Uncapitalize

    将字符串中的第一个字符转换为小写的等效字符。

    type UppercaseGreeting = "HELLO WORLD";
    type UncomfortableGreeting = Uncapitalize<UppercaseGreeting>; // type UncomfortableGreeting = "hELLO WORLD"
    
    • 1
    • 2
  • 相关阅读:
    植物大战 类和对象2——C++
    【牛客刷题--SQL篇】多表查询链接查询 SQL22统计每个学校的答过题的用户的平均答题数
    “参与 Debian 项目 20 年后,被降级的我选择退出”
    C. Discrete Acceleration(浮点二分)
    19.在springboot中集成dubbo(zookeeper)
    Docker高级篇之Docker微服务实战
    Linux高级编程--gdb调试
    python中用于计算的函数
    FineReport可视化数据图表- 函数计算组成和语法示例
    BIGEMAP在土地规划中的应用
  • 原文地址:https://blog.csdn.net/qq_28550263/article/details/128169632