1.核心作用:定义 "允许的值" 的范围和操作规则
2.与 JavaScript 的关系:TS 的类型系统是对 JS 值的补充描述,所有 JS 值在 TS 中都有对应的类型映射
3.关键特性:TypeScript 采用结构类型系统(Structural Typing),即类型兼容性基于结构是否匹配,而非名义上的类型名称(与 Java 等名义类型系统不同)
一、Type 类型的实现原理
二、Type 类型的常用使用方式
1. 基础类型注解
// 变量类型 let count: number = 10; let message: string = "hello"; let isDone: boolean = false;// 函数类型 function add(a: number, b: number): number {return a + b; }
2. 自定义类型(type 关键字)
// 类型别名 type ID = number | string; // 联合类型// 对象类型 type User = {id: ID;name: string;age?: number; // 可选属性readonly createdAt: Date; // 只读属性 };// 函数类型 type MathOperation = (x: number, y: number) => number; const multiply: MathOperation = (a, b) => a * b;
3. 高级类型用法
4. 类型守卫与类型缩小
总结