Typescript高级用法

Posted yimuqing

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Typescript高级用法相关的知识,希望对你有一定的参考价值。

keyof

interface Person {
    name: string;
    age: number
}
type option = keyof Person; //  type option = 'name'|'age'

Partial & Pick

type Partial<T> = {
  [P in keyof T]?: T[P];
};

type Pick<T, K extends keyof T> = {
    [P in K]: T[P];
}

interface User {
  id: number;
  age: number;
  name: string;
};

type PartialUser = Partial<User> //  type PartialUser = { id?: number; age?: number; name?: string; }

type PickUser = Pick<User, 'name'|'age'> // type PickUser = { name: string; age: number; }

Condition Type

   T extends U ? X : Y
   type isTrue<T> = T extends true ? true : false 
   type t = isTrue<number> // type t = false
   type t1 = isTrue<false>  // type t = false
   type t2 = isTrue<true> // type t = true

never & Exclude & Omit

    type Exclude<T, U> = T extends U ? never : T;
    type A = Exclude<'x' | 'a', 'x' | 'y' | 'z'>  //  type A = 'a'
    
    type Omit<T, K extends keyof any> = Pick<T, Exclude<keyof T, K>>;     
    interface User {
      id: number;
      age: number;
      name: string;
    };
    type OmitUser = Omit<User, "id"> // type OmitUser = { age: number; name: string; }    

typeof

    const a: number = 3
    const b: typeof a = 4 // const b: number = 4

is

    // !!! 使用 is 来确认参数 s 是一个 string 类型
    function isString(s): s is string {
      return typeof s === 'string';
    }

Dictionary & Many

    interface Dictionary<T> {
        [index: string]: T;
    };
    
    interface NumericDictionary<T> {
        [index: number]: T;
    };
    
    const data:Dictionary<number> = {
        a: 3,
        b: 4
    }

enum

    const enum TODO_STATUS {
        TODO = 'TODO',
        DONE = 'DONE',
        DOING = 'DOING'
    }
 
    function todos (status: TODO_STATUS): Todo[];
 
    todos(TODO_STATUS.TODO)

以上是关于Typescript高级用法的主要内容,如果未能解决你的问题,请参考以下文章

Typescript高级用法

typescript中工具类型高级用法

TypeScript学习笔记——TS类型/高级用法及实战优缺点

TypeScript学习笔记——TS类型/高级用法及实战优缺点

TypeScript学习笔记——TS类型/高级用法及实战优缺点

阿里前端大佬TypeScript学习笔记——TS类型/高级用法及实战优缺点