Skip to content

TypeScript 入门指南

TypeScript 是 JavaScript 的超集,提供了静态类型检查和最新的语言特性。

为什么使用 TypeScript?

  1. 类型安全 - 编译时发现错误,减少运行时 bug
  2. 更好的 IDE 支持 - 智能提示、重构支持
  3. 代码文档化 - 类型即文档
  4. 现代化特性 - 支持最新的 ECMAScript 特性

基础类型

原始类型

typescript
// 字符串
const name: string = 'Alice';

// 数字
const age: number = 25;

// 布尔值
const isStudent: boolean = true;

// undefined 和 null
const u: undefined = undefined;
const n: null = null;

数组

typescript
// 两种声明方式
const numbers: number[] = [1, 2, 3, 4, 5];
const names: Array<string> = ['Alice', 'Bob', 'Carol'];

元组 (Tuple)

typescript
// 固定长度和类型的数组
const person: [string, number] = ['Alice', 25];

对象类型

typescript
interface User {
  name: string;
  age: number;
  email?: string;  // 可选属性
  readonly id: number;  // 只读属性
}

const user: User = {
  name: 'Alice',
  age: 25,
  id: 1
};

类型别名与联合类型

typescript
// 类型别名
type ID = string | number;
type Point = { x: number; y: number };

// 联合类型
type Status = 'pending' | 'success' | 'error';

// 交叉类型
type Employee = User & {
  department: string;
  salary: number;
};

泛型

typescript
// 泛型函数
function identity<T>(arg: T): T {
  return arg;
}

// 泛型接口
interface Container<T> {
  value: T;
  add(item: T): void;
}

// 泛型约束
interface Lengthwise {
  length: number;
}

function logLength<T extends Lengthwise>(arg: T): number {
  return arg.length;
}

枚举

typescript
enum Direction {
  Up = 'UP',
  Down = 'DOWN',
  Left = 'LEFT',
  Right = 'RIGHT'
}

const move = (direction: Direction) => {
  // ...
};

move(Direction.Up);

实用技巧

类型守卫

typescript
interface Cat {
  meow(): void;
}

interface Dog {
  bark(): void;
}

function isCat(animal: Cat | Dog): animal is Cat {
  return (animal as Cat).meow !== undefined;
}

类型断言

typescript
const value: unknown = 'Hello';
const str: string = value as string;
const str2: string = <string>value;  // JSX 中不可用

总结

TypeScript 为 JavaScript 开发带来了类型安全和更好的开发体验。推荐在所有新项目中优先使用 TypeScript。


标签: TypeScript JavaScript

基于 VitePress 构建