1、基础知识
基础类型: number string boolean array object
- enum: 枚举
- type, interface
- 联合类型 | (联合类型一次只能一种类型;而交叉类型每次都是多个类型的合并类型。)
- 交叉类型 & (联合类型一次只能一种类型;而交叉类型每次都是多个类型的合并类型。)
- typeof
typeof 操作符可以用来获取一个变量声明或对象的类型。
function toArray(x: number): Array<number> {return [x];}type Func = typeof toArray; // -> (x: number) => number[]
- keyof
keyof 操作符可以用来一个对象中的所有 key 值:
interface Person {name: string;age: number;}type K1 = keyof Person; // "name" | "age"
- in
in 用来遍历枚举类型:
type Keys = "a" | "b" | "c"type Obj = {[p in Keys]: any} // -> { a: any, b: any, c: any }
- extends
有时候我们定义的泛型不想过于灵活或者说想继承某些类等,可以通过 extends 关键字添加泛型约束。
interface ILengthwise {length: number;}function loggingIdentity<T extends ILengthwise>(arg: T): T {console.log(arg.length);return arg;}loggingIdentity(3);loggingIdentity({length: 10, value: 3});
- Paritial
Partial 的作用就是将某个类型里的属性全部变为可选项 ?。
- Reuqired
Required 的作用就是将某个类型里的属性全部变为必选项。
- Readonly
Readonly 的作用是将某个类型所有属性变为只读属性,也就意味着这些属性不能被重新赋值。
- Record
Record
interface PageInfo {title: string;}type Page = "home" | "about" | "contact";const x: Record<Page, PageInfo> = {about: { title: "about" },contact: { title: "contact" },home: { title: "home" }};
- Exclude
Exclude
type T0 = Exclude<"a" | "b" | "c", "a">; // "b" | "c"type T1 = Exclude<"a" | "b" | "c", "a" | "b">; // "c"
- Extract
Extract
type T0 = Extract<"a" | "b" | "c", "a" | "f">; // "a"type T1 = Extract<string | number | (() => void), Function>; // () => void
