Skip to content

进阶用法 #40

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
Yolo-0317 opened this issue May 22, 2021 · 0 comments
Open

进阶用法 #40

Yolo-0317 opened this issue May 22, 2021 · 0 comments

Comments

@Yolo-0317
Copy link
Owner

泛型

泛型就是不预先确定的数据类型,具体的类型在使用的时候再确定的一种类型约束规范

泛型的好处:

  • 函数和类可以轻松的支持多种类型,增强程序的扩展性
  • 不必写多条函数重载,冗长的联合类型声明,增强代码的可读性
  • 灵活控制类型之间的约束

泛型可以应用于 function、interface、type 或者 class 中。但是注意,「泛型不能应用于类的静态成员」

工具泛型

interface TestInterface {
    a: string;
    b: number;
    c?: string;
}
interface Person {
    name: string;
    age: number;
}
const testObj:TestInterface = {a: '1', b: 1}

Partial

Partial的作用就是将传入的属性变为可选。

const testObj:Partial<TestInterface> = {a: '1'}

Required

Required 的作用是将传入的属性变为必选项

// Right
const testObjReqired:Required<TestInterface> = { a:'1', b:1, c: '1'}

Readonly

将传入的属性变为只读选项

Record

该类型可以将 K 中所有的属性的值转化为 T 类型

/**
 * Construct a type with a set of properties K of type T
 */
type Record<K extends keyof any, T> = {
    [P in K]: T;
};
const testObjRecord:Record<'a', Person> = {a: {name: '1', age: 1}}

Pick

从 T 中取出 一系列 K 的属性

const testObjPick:Pick<TestInterface, 'a'> = {a: '1'}

Exclude

Exclude 将某个类型中属于另一个的类型移除掉。

Extract

Extract 的作用是提取出 T 包含在 U 中的元素,换种更加贴近语义的说法就是从 T 中提取出 U

类型断言

推荐类型断言的预发使用 as关键字,而不是<> ,防止歧义
类型断言并非类型转换,类型断言发生在编译阶段。类型转换发生在运行时

函数重载

函数重载的基本语法:

declare function test(a: number): number;
declare function test(a: string): string;

const resS = test('Hello World');  // resS 被推断出类型为 string;
const resN = test(1234);           // resN 被推断出类型为 number;

这里我们申明了两次?!为什么我不能判断类型或者可选参数呢?后来我遇到这么一个场景,

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

declare function test(para: User | number, flag?: boolean): number;

在这个 test 函数里,我们的本意可能是当传入参数 para 是 User 时,不传 flag,当传入 para 是 number 时,传入 flag。TypeScript 并不知道这些,当你传入 para 为 User 时,flag 同样允许你传入:

const user = {
  name: 'Jack',
  age: 666
}

// 没有报错,但是与想法违背
const res = test(user, false);
使用函数重载能帮助我们实现:

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

declare function test(para: User): number;
declare function test(para: number, flag: boolean): number;

const user = {
  name: 'Jack',
  age: 666
};

// bingo
// Error: 参数不匹配
const res = test(user, false);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant