口碑好的网站建设哪家好网页设计与制作模板
类型推断
TypeScript 的类型推断是一种编译器能够自动分析代码并确定变量的类型的功能。它允许你在声明变量时省略类型注释,让 TypeScript 根据变量的值来推断出合适的类型。
以下是 TypeScript 类型推断的一些示例和情况:
- 基本类型推断:
let age = 25; // TypeScript 推断 age 为 number 类型
let name = "Alice"; // TypeScript 推断 name 为 string 类型
let isStudent = true; // TypeScript 推断 isStudent 为 boolean 类型
- 数组类型推断:
let fruits = ['apple', 'banana', 'orange']; // TypeScript 推断 fruits 为 string[] 类型
- 函数类型推断:
function add(a: number, b: number) {return a + b;
}// TypeScript 推断 add 函数的类型为 (a: number, b: number) => number
- 对象属性类型推断:
let person = {name: 'Bob',age: 30
};// TypeScript 推断 person 为 { name: string, age: number } 类型
- 联合类型推断:
let value: number | string = 42; // TypeScript 推断 value 为 number 类型
value = 'forty-two'; // TypeScript 推断 value 为 string 类型
- 函数返回类型推断:
function greet(name: string) {return `Hello, ${name}!`;
}// TypeScript 推断 greet 函数的返回类型为 string
类型别名
在 TypeScript 中,类型别名(Type Alias)是一种用于为现有类型定义一个新的名称的机制。
以下是 TypeScript 类型别名的基本用法和特点:
// 基本类型的类型别名
type Age = number;
type Name = string;let age: Age = 25;
let name: Name = 'Alice';// 复杂类型的类型别名
type Person = {name: string;age: number;
};let person: Person = {name: 'Bob',age: 30
};// 联合类型的类型别名
type Result = number | string;let result1: Result = 42;
let result2: Result = 'forty-two';// 函数类型的类型别名
type Greeter = (name: string) => string;const greet: Greeter = (name) => `Hello, ${name}!`;// 联合类型和交叉类型的类型别名
type Combined = Age | Person;let combined1: Combined = 25;
let combined2: Combined = {name: 'Carol',age: 28
};// 根据级别判断 1 是否包含在 number / Object 中
type num = 1 extends number ? 1 : 0; // num = 1
type num1 = 1 extends Object ? 1 : 0; // num1 = 1
类型别名的特点:
-
类型别名使用
type
关键字来声明。 -
类型别名可以代表任何类型,包括基本类型、复杂类型、函数类型等,还可以用于创建联合类型、交叉类型和其他自定义类型。
-
类型别名不会创建新的类型,它只是为现有类型提供了一个别名。
type
和 interface
的区别
在 TypeScript 中,type
和 interface
都用于创建自定义类型,但它们在某些方面有一些不同。以下是 type
和 interface
的区别:
-
语法:
- 使用
type
关键字创建类型别名。 - 使用
interface
关键字创建接口。
- 使用
-
扩展:
type
可以表示联合类型、交叉类型、基本类型等,也可以用于为现有类型创建别名。但是,type
不支持扩展,即不能用extends
来扩展其他类型,但是可以type s = number[] & B
(此时 B 是 interface 的定义的接口)。interface
可以表示对象类型、函数类型、类的成员、可索引类型等,它支持继承和实现其他接口。
-
实现:
type
不支持implements
,不能用于强制一个类去实现某些类型。interface
支持implements
,可以用于确保一个类满足某些特定的契约。
-
合并:
interface
具有合并机制,当你声明同名的多个接口时,它们会自动合并为一个接口。type
不具有合并机制,多次声明同名的type
会报错。
-
适用场景:
- 如果你只需要描述对象的结构,特别是在面向对象的编程中,使用
interface
更加合适。 - 如果你需要创建复杂的联合类型、交叉类型,或者给现有类型取别名,使用
type
更加合适。
- 如果你只需要描述对象的结构,特别是在面向对象的编程中,使用
举个例子,假设我们要描述一个 Person
对象:
// 使用 interface
interface PersonInterface {name: string;age: number;
}// 使用 type
type PersonType = {name: string;age: number;
};