码迷,mamicode.com
首页 > 其他好文 > 详细

Typescript高级用法

时间:2020-03-14 20:28:30      阅读:82      评论:0      收藏:0      [点我收藏+]

标签:ret   dex   false   iss   status   一个   eve   ever   参数   

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高级用法

标签:ret   dex   false   iss   status   一个   eve   ever   参数   

原文地址:https://www.cnblogs.com/yimuqing/p/12493637.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!