TypeScript 基础类型
TypeScript 是 JavaScript 的超集,添加了静态类型系统。
基本类型
ts
// 字符串
const name: string = "TypeScript"
// 数字
const year: number = 2026
// 布尔值
const isFun: boolean = true
// 数组
const list: number[] = [1, 2, 3]
const list2: Array<number> = [1, 2, 3]
// 元组
const pair: [string, number] = ["hello", 42]
// 枚举
enum Color {
Red,
Green,
Blue,
}特殊类型
ts
// any - 任何类型(尽量少用)
let loose: any = "可变的"
// unknown - 安全的 any
let notSure: unknown = 4
// void - 没有返回值
function log(msg: string): void {
console.log(msg)
}
// never - 永远不会返回
function throwError(msg: string): never {
throw new Error(msg)
}类型系统是 TypeScript 的核心价值所在,用好类型能让代码更健壮、更容易维护。