常用的TS基础理论知识

174 阅读2分钟
基本数据类型 : number、string、array、object、boolean
    const num: number = 1
    const str: string = 'a'
枚举 enum
    // 活动状态
    enum ActivityStatus {
        // 活动未开始
        NOT_START = 'noStart',
        // 活动已开始
        STARTED = 'started',
    }
    
    const status = ActivityStatus.NOT_START
type、interface
    type UserInfo = {
        name: string,
        age: number,
    }
    
    const userInfo: UserInfo = {
        name: '潘',
        age: 28,
    }
    
    interface UserInfo {
        name?: string,
        age?: number,
    }
    
    const userInfo: UserInfo = {}
联合类型 | (联合类型一次只能使用一种类型,而交叉类型 每次都是多个类型的合并类型)
交叉类型 & (联合类型一次只能使用一种类型,而交叉类型 每次都是多个类型的合并类型)
  interface UserInfoA {
      name?: string,
      age?: number,
  }
  interface UserInfoB {
      sex?: 'string'
  }
    // 可以是UserInfoA或UserInfoB
function test(param: UserInfoA & UserInfoB ){}
    // 只能是其中一个类型
function test(param: UserInfoA | UserInfoB ){}
typeof
// js
    typeof 'a' // string
// ts
    function toArray (x: number): Array<number> {
        return [x];
    }
    
    type Func = typeof toArray; // (x: number) => number[]
keyof
    // 可以用来后去一个对象的key值
    interface Person {
        name: string;
        age: number;
    }
    type KPerson = keyof Person; // name | age;
    const str: KPerson = 'name';
    const str: KPerson = 'age';
in

用来遍历枚举类型

    type Keys = 'a' | 'b' | 'c'
    type Obj = {
        [key in Keys]: any;
    }
extends

继承类型

    interface Ilength {
        length: number;
    }
    function loggingIdntity<T extengs ILength>(arg: T):T {//T必须包含Ilength属性
        console.log(arg.length);
        return arg;
    }
    loggingIdntity(3); // 报错
    loggingIdntity({ length: 10, value: 3 });
Paritial

Paritial 的作用是将某个类型的属性全部变为可选项。

     interface Ilength {
        length: number;
    }
    
    type PageInfo = Paritial<Ilength>
    //相当于
    interface Ilength {
        length?: number;
    }
Required 与Paritial相反
Readonly
    interface Ilength {
      length: number;
    }
    type PageInfo = Readonly<Ilength>
    const pageInfo: PageInfo = { title:'' }
    pageInfo.title = '111'// 报错 ,只可读
Record

Record<K extends keyof any, T>的作用是将K的所有属性的值,转化为T类型;

    interface Ilength {
        length?: number;
    }
    type Page = 'a' | ‘b’ | ‘c’;
    const x: Record<Page, Ilength> = {
        a: {length: 'a'},
        b: {length: 'b'},
        c: {length: 'c'},
    }
Exclude

Exclude<T, U>将某个类型中属于另一个的类型移除掉

    typeof TO = Exclude<'a' | 'b' | 'c' , ‘a’>; // 'b' | 'c' 
    typeof T1 = Exclude<'a' | 'b' | 'c' , ‘a’ | 'b'>; // 'c' 
Extract

Extract<T, U>的作用是从T中提取U,大概就是取T和U的交集的意思。

    type TO = Exclude<'a' | 'b' | 'c' , ‘a’>; // 'a' 
    type T1 = Extract<string | number | (()=> void), Function>; // () => void