# TSCODE **Repository Path**: _asd/ts ## Basic Information - **Project Name**: TSCODE - **Description**: No description available - **Primary Language**: Unknown - **License**: Not specified - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2024-10-08 - **Last Updated**: 2024-10-08 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README ### 一、类型守卫 #### 1. typeof 类型守卫 使用 `typeof` 关键字进行类型检查。 #### 2. instanceof 类型守卫 使用 `instanceof` 关键字进行类型对象的检测。 #### 3. 使用自定义谓词函数类型守卫 定义自己的函数,根据变量类型进行判断,具体实例如下: ```typescript interface Circle { kind: "circle"; radius: number; } interface Rectangle { kind: "rectangle"; width: number; height: number; } type Shape = Circle | Rectangle; function calculateArea(shape: Shape) { if (isCircle(shape)) { console.log(Math.PI * shape.radius ** 2); } else { console.log(shape.width * shape.height); } } function isCircle(shape: Shape): shape is Circle { return shape.kind === "circle"; } const circle: Circle = { kind: "circle", radius: 5 }; const rectangle: Rectangle = { kind: "rectangle", width: 10, height: 20 }; calculateArea(circle); // 输出: 78.53981633974483 calculateArea(rectangle); // 输出: 200 ``` #### 4. 联合类型守卫 类型守卫最常用于联合类型中,因为联合类型可能包含多个不同的类型选项。具体实例如下; ```typescript interface Car { type: "car"; brand: string; wheels: number; } interface Bicycle { type: "bicyle"; color: string; } interface Motorcycle { type: "motorcycle"; engine: number; } type Vehicle = Car | Bicycle | Motorcycle; function pringVehicleInfo(vehicle: Vehicle) { switch (vehicle.type) { case "car": console.log(`Brand:${vehicle.brand}, wheels:${vehicle.wheels}`); break; case "bicyle": console.log(`Color: ${vehicle.color}`); break; case "motorcycle": console.log(`Engine:${vehicle.engine}`); break; default: const _exhaustiveCheck: never = vehicle; } } const car: Car = { type: "car", brand: "Toyota", wheels: 5 }; const bicyle: Bicycle = { type: "bicyle", color: "red" }; const motorcycle: Motorcycle = { type: "motorcycle", engine: 1000 }; console.log(car); console.log(bicyle); console.log(motorcycle); ``` #### 5. 使用 in 操作符进行类型守卫 in 操作符可以用于在 TypeScript 中判断一个属性是否存在于对象中,从而进行类型判 断和类型收窄。例如: ```typescript interface Circle { kind: "circle"; radius: number; } interface Rectangle { kind: "rectangle"; width: number; height: number; } type ShapeEx = Circle | Rectangle; function printArea(shape: Shape) { if ("radius" in shape) { console.log(Math.PI * shape.radius ** 2); } else { console.log(shape.width * shape.height); } } const circleex: Circle = { kind: "circle", radius: 5 }; const rectangleex: Rectangle = { kind: "rectangle", width: 10, height: 20 }; printArea(circleex); // 输出: 78.53981633974483 printArea(rectangleex); // 输出: 200 ``` #### 6. 控制流类型守卫 当执行特定的操作后,编译器会智能地调整变量的类型范围,这被称为控制流类型收窄。 ### 二、类型体操 #### 1. 条件类型 条件类型允许我们根据输入类型的条件判断结果来选择不同的类型。条件类型的语法形式为: ```typescript T extends U ? X : Y ``` 具体实例如下: ```typescript type Check = T extends string ? true : false; type Result = Check; ``` #### 2. keyof 操作符和索引访问类型 `keyof` 关键字主要是用于获取类型的所有属性名,结合索引访问类型可以从一个类型中获取属性的具体类型。具体实例如下: ```typescript interface Person { name: string; age: number; } type PersonKeys = keyof Person; type PersonNameType = Person["name"]; ``` #### 3. infer 关键字 `infer` 关键字用于在条件类型中推断类型,并将其赋值给一个类型变量。 ```typescript type ReturnTypeEx = T extends (...args: any[]) => infer R ? R : never; function add(a: number, b: number) { return a + b; } type AddReturnBalue = ReturnTypeEx; ``` ### 三、TypeScript 内置泛型函数 #### 1. Partial Partial 是 TypeScript 中的一个内置泛型类型,它可以将给定类型 T 中的所有属性转换为可选属性。具体实例: ```typescript interface Person { name: string; age: number; } type PartialPerson = Partial; const partialPerson: PartialPerson = { name: "John" }; ``` #### 2. Required Required 是 TypeScript 中的另一个内置泛型类型,它可以将给定类型 T 中的所有可选属性转换为必需属性。具体实例: ```typescript interface PersonEx { name?: string; age?: number; } type RequeiredPerson = Required; const requeiredPerson: RequeiredPerson = { name: "John", age: 24 }; ``` #### 3. Pick Pick 是 TypeScript 中的另一个内置泛型函数,它可以从给定类型 T 中选择指定的属性 K 组成一个新的类型。具体实例: ```typescript interface PersonEx1 { name: string; age: number; address: string; } type NameAndAge = Pick; const person: NameAndAge = { name: "John", age: 34 }; ``` #### 4. Exclude Exclude 是 TypeScript 中的一个内置泛型函数,用于从类型 T 中排除类型 U。它返回一个新类型,该新类型包含在 T 中存在但不在 U 中存在的成员类型。 ```typescript type T = Exclude<"a" | "b" | "c", "a" | "b">; // T 的类型为 "c" ``` #### 5. Omit Omit 是 TypeScript 中的另一个内置泛型函数,它返回一个新类型,该新类型排除了类型 T 中指定的属性 K。 ```typescript interface Person { name: string; age: number; address: string; } type PersonWithoutAddress = Omit; ``` #### 6. Readonly Readonly 是 TypeScript 中的另一个内置泛型函数,它将类型 T 中的所有属性转换为只读属性。 ```typescript interface Person { name: string; age: number; } type ReadonlyPerson = Readonly; ``` ### 四、鸭子类型 只要一个对象的结构满足接口要求,就可以把这个对象看做这个接口的实例,不管这个对象的实际类型是什么情况。具体实例如下: ```typescript interface Duck { walk: () => void; quack: () => void; } function doDuckThings(duck: Duck) { duck.quack(); duck.walk(); } const myDuck = { walk: () => console.log("Walking like a duck"), quack: () => console.log("Quacking like a duck"), swim: () => console.log("Swimming like a duck"), }; doDuckThings(myDuck); ``` ### 五、协变与逆变 协变:父子继承(泛型也算) 逆变: