基础知识

基础类型:number string boolean array object

  1. enum 枚举
    接口给前端返回一盒status字段

     enum ActivityStatus {
         NOT_START = 'notStart',
         STARTED = 'stated'
     }
    
     const status = ActivityStatus.NOT_START;
  2. type, interface
    // type UserInfo = {
    //     name: string;
    //     height?: number
    // }
    
    interface UserInfo {
        name: string;
        height?: number
    }

    const userInfo = {
        name: 'cxx'
    }
  1. 联合类型 | (联合类型一次只能使用一种类型,而交叉类型每次都是多个合并类型)
  2. 交叉类型 & (联合类型一次只能使用一种类型,而交叉类型每次都是多个合并类型)
    interface UserInfoA {
        name?: string;
        height?: number
    }
    interface UserInfoB {
        width: number
    }

    function test (param: UserInfoA | UserInfoB){
        // ...
    }
  1. typeof

     typeof 'a' //string
     function toArray(x: number):Array<number>{
         return {x};
     }
    
     type Func = typeof toArray; // (x: number) => number[]
  2. keyof
    // 可以用来获取一个对象中所有的key值
    interface Person{
        name: string;
        age: number;
    }

    type KPerson = keyof Person; // 'name' | 'age'
  1. in 用来遍历枚举类型

     type Keys = 'a' | 'b' | 'c';
    
     type obj = {
         [key in Keys]: any;
     }
  2. extends 继承类型

     interface TLength{
         length: number
     }
    
     function loggingIdentity<T extends TLength>(arg: T): T{
         console.log(arg.length);
         return arg;
     }
    
     loggingIdentity(3);
     loggingIdentity({length: 10, value: 3});
  3. Paritial
    Paritial<T> 的作用是将某个类型的属性全部变为可选项

     interface PageInfo{
         title: string;
     }
    
     type OptionalPageInfo = Paritial<PageInfo>;
  4. Required 全部变为必选项
  5. Readonly 全部变为只读

     interface PageInfo{
         title: string;
     }
    
     type ReadonlyPageInfo = Readonly<PageInfo>;
    
     const pageInfo: ReadonlyPageInfo = { title: 'cxx' };
     pageInfo.title = 'ch'; // error
  6. Record
    Record<K extends keyof any, T> 将K中的所有属性的值转化为T类型

     interface PageInfo{
         title: string;
     }
     type Page = "home" | "about" | "contact";
     const x: Record<Page, PageInfo> = {
         home: {title: '111'},
         about: {title: '222'},
         contact: {title: '333'},
     }
  7. Exclude
    Exclude<T, U> 将某个类型中属于另一个的类型移除

     type T0 = Exclude<"a" | "b" |"c", "a">    // "b | "c"
     type T1 = Exclude<"a" | "b" |"c", "a" | "b">    // "c"
  8. Extract
    Extract<T, U> 从T中提取U,大概是取交集的意思

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

土豆不是瓜
0 声望0 粉丝