zoukankan      html  css  js  c++  java
  • TypeScript类型映射

    ts可以使用泛型来做类型映射,将对象或数组中类型转换为另一个类型。

    例如:

    定义一个类型

    interface Student{
        name: string,
        age: number
    }

    1. 把一个类型的每个属性都变为可空的

    type Nullable<T> = {
        [p in keyof T]: T[P] | null
    }
    
    type NullableStudent = Nullable<Student>

    2. 把一个类型的每个属性都变为只读的

    //定义readonly映射
    type Readonly<T> = {
        readonly [P in keyof T]: T[P]
    }
    
    type ReadonlyStudent = Readonly<Student>

    3. 把一个类型的属性都变为可选的

    type Partical<T> = {
        [P in keyof T]?: T[P]
    }
    
    type ParticalStudent = Partical<Student>

    4. 把一个类型的每个项都变为Promise

    //定义toPromise映射
    type ToPromise<T> = { [K in keyof T]: Promise<T[K]> };
    
    type Coordinate = [number, number]
    
    type PromiseCoordinate = ToPromise<Coordinate>; // [Promise<number>, Promise<number>]
  • 相关阅读:
    mongostat
    mongodb的游标方法
    mongodb升级
    mongodb的白名单
    mongodb的副本集方法
    mongodb的collection方法
    mongodb的db方法
    mongoexport
    mongoimport
    mongodb分片集群管理
  • 原文地址:https://www.cnblogs.com/mengff/p/12937021.html
Copyright © 2011-2022 走看看