We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
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
泛型就是不预先确定的数据类型,具体的类型在使用的时候再确定的一种类型约束规范
泛型的好处:
泛型可以应用于 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的作用就是将传入的属性变为可选。
const testObj:Partial<TestInterface> = {a: '1'}
Required 的作用是将传入的属性变为必选项
// Right const testObjReqired:Required<TestInterface> = { a:'1', b:1, c: '1'}
将传入的属性变为只读选项
该类型可以将 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}}
从 T 中取出 一系列 K 的属性
const testObjPick:Pick<TestInterface, 'a'> = {a: '1'}
Exclude 将某个类型中属于另一个的类型移除掉。
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);
The text was updated successfully, but these errors were encountered:
No branches or pull requests
泛型
泛型的好处:
泛型可以应用于 function、interface、type 或者 class 中。但是注意,「泛型不能应用于类的静态成员」
工具泛型
Partial
Partial的作用就是将传入的属性变为可选。
Required
Required 的作用是将传入的属性变为必选项
Readonly
将传入的属性变为只读选项
Record
该类型可以将 K 中所有的属性的值转化为 T 类型
Pick
从 T 中取出 一系列 K 的属性
Exclude
Exclude 将某个类型中属于另一个的类型移除掉。
Extract
Extract 的作用是提取出 T 包含在 U 中的元素,换种更加贴近语义的说法就是从 T 中提取出 U
类型断言
推荐类型断言的预发使用 as关键字,而不是<> ,防止歧义
类型断言并非类型转换,类型断言发生在编译阶段。类型转换发生在运行时
函数重载
函数重载的基本语法:
这里我们申明了两次?!为什么我不能判断类型或者可选参数呢?后来我遇到这么一个场景,
在这个 test 函数里,我们的本意可能是当传入参数 para 是 User 时,不传 flag,当传入 para 是 number 时,传入 flag。TypeScript 并不知道这些,当你传入 para 为 User 时,flag 同样允许你传入:
The text was updated successfully, but these errors were encountered: