6. 学习 typescript 复杂用法

这是我参与8月更文挑战的第6天,活动详情查看:8月更文挑战html

1.Partial<Type>:将类型的属性「变成可选」

#源码:
type Partial<T> = {
  [P in keyof T]?: T[P];
};
复制代码
  • 索引类型查询操做符: keyof
type Partial<T> = {
  [P in keyof T]?: T[P];/ / 将每一对中的 key 变为可选,即添加 ?
}
复制代码
  • 使用
interface User { 
  name: string 
  age: number 
  department: string 
}

type optional = Partial<User>

// optional的结果以下
type optional = {
    name?: string | undefined;
    age?: number | undefined;
    department?: string | undefined;
}

复制代码

2.Required<Type>:将类型的属性变成必选

源码:
type Required<T> = {
  [P in keyof T]-?: T[P];
};
//  这里的 - 号是去除条件
复制代码
  • 使用
interface Props {
  a?: number;
  b?: string;
}
const obj: Props = { a: 5 };
const obj2: Required<Props> = { a: 5 }; //报错
复制代码

3.Readonly<Type>:将类型T中的成员变为只读

源码:
type Readonly<T> = {
  readonly [P in keyof T]: T[P]; // 就是在前面加了一个修饰符
};
复制代码
  • 使用
interface Todo {
  title: string;
}

const todo: Readonly<Todo> = {
  title: "Delete inactive users",
};

todo.title = "Hello"; // 这里只读属性,就报错了
复制代码

4.Record:将一个类型的全部属性值都映射到另外一个类型上并创造一个新的类型

源码:
type Record<K extends string, T> = {
  [P in K]: T;
}
复制代码
  • 使用
interface PageInfo {
  title: string;
}

type Page = "home" | "about" | "contact";

const nav: Record<Page, PageInfo> = {
  about: { title: "about" },
  contact: { title: "contact" },
  home: { title: "home" },
};

// Record 后面的泛型就是对象键和值的类型


# 有 ABC 三个属性,属性的值必须是数字
type keys = 'A' | 'B' | 'C'
const result: Record<keys, number> = {
  A: 1,
  B: 2,
  C: 3
}

复制代码

5.Pick<Type, Keys>:从一个复合类型中,取出几个想要的类型的组合

源码:
type Pick<T, K extends keyof T> = { 
  [P in K]: T[P];
};
复制代码
  • 使用
interface Todo {
  title: string;
  description: string;
  completed: boolean;
}
type TodoPreview = Pick<Todo, "title" | "completed">;

const todo: TodoPreview = {
  title: "Clean room",
  completed: false,
};
todo;
复制代码

6.Omit<Type, Keys>:从另外一个对象类型中剔除某些属性,并建立一个新的对象类型

用Pick<T, Exclude<keyof T, K>>来表示
复制代码
  • 使用
type  UserProps =  {
  name?:string;
  age?:number;
  sex?:string;
}
// 可是我不但愿有sex这个属性我就能够这么写
type NewUserProps =  Omit<UserProps,'sex'> 
// 等价于
type  NewUserProps =  {
  name?:string;
  age?:number;
}
复制代码

7.ReturnType 用来获得一个函数的返回值类型

declare function f1(): { a: number; b: string };

type T0 = ReturnType<() => string>;
  type T0 = string

type T4 = ReturnType<typeof f1>;
  type T4 = { a: number; b: string; }
复制代码

8.Exclude<Type, ExcludedUnion>: 去除Type中包含ExcludedUnion的属性

type T0 = Exclude<"a" | "b" | "c", "a">; // 去除Type中包含 "a" 的属性
  type T0 = "b" | "c"
复制代码

9.Extract<Type, Union>:取TypeUnion都存在的属性

type T0 = Extract<"a" | "b" | "c", "a" | "f">;
  type T0 = "a"
复制代码

参考

相关文章
相关标签/搜索