TypeScript 入门指南

0 阅读2分钟

TypeScript 是 JavaScript 的静态类型超集,最终编译成纯 JavaScript。它为 JS 添加了类型系统,让代码更健壮、更易维护。

为什么用 TypeScript?

  • 早发现错误:编码时就能捕获类型不匹配等问题
  • 更好的智能提示:IDE 自动补全、重构更可靠
  • 自文档化:类型即注释,函数签名清晰表达意图

安装与编译

npm install -g typescript       # 安装
tsc hello.ts                    # 编译成 hello.js
tsc --init                      # 生成 tsconfig.json 配置文件

基础类型注解

let name: string = "张三";
let age: number = 18;
let isStudent: boolean = true;
let hobbies: string[] = ["读书", "游泳"];        // 数组
let tuple: [string, number] = ["小明", 25];       // 元组
let anyValue: any = "随便什么类型";               // 尽量少用 any
let voidValue: void = undefined;                  // 函数无返回值时用

函数类型

// 参数和返回值都要标注类型
function greet(name: string): string {
  return `你好,${name}`;
}

// 可选参数用 ?
function buildName(first: string, last?: string): string {
  return first + (last ? " " + last : "");
}

// 箭头函数
const add = (a: number, b: number): number => a + b;

接口(Interface)—— 定义对象形状

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

function introduce(person: Person): void {
  console.log(`${person.name}${person.age}岁`);
}

const me: Person = { name: "李华", age: 20, id: 1 };
introduce(me);
// me.id = 2;  ❌ 错误,id 是只读的

类型别名(Type)与接口的区别

// 类型别名可以表示联合类型、原始类型等
type ID = string | number;
type Status = "success" | "error";

let userId: ID = "abc123";
userId = 456;           // ✅ 合法

// 接口适用于对象类型,可被扩展;类型别名更通用

类(Class)

class Animal {
  constructor(public name: string) {}   // 简写:自动声明并赋值

  move(distance: number): void {
    console.log(`${this.name} 移动了 ${distance} 米`);
  }
}

class Dog extends Animal {
  bark(): void {
    console.log("汪汪!");
  }
}

const dog = new Dog("旺财");
dog.bark();
dog.move(10);

泛型(Generics)—— 复用类型逻辑

// 普通写法:丢失类型信息
function identity(arg: any): any { return arg; }

// 泛型写法:保持类型安全
function identity<T>(arg: T): T {
  return arg;
}

let output1 = identity<string>("hello");  // 显式指定 T 为 string
let output2 = identity(123);              // 类型推断为 number

// 泛型接口
interface Box<T> {
  value: T;
}
let box: Box<number> = { value: 100 };

常用技巧

联合类型与类型守卫

function printId(id: number | string) {
  if (typeof id === "string") {
    console.log(id.toUpperCase());   // 这里是 string
  } else {
    console.log(id);                 // 这里是 number
  }
}

非空断言(谨慎使用)

let element = document.getElementById("app")!;  // 确定不为 null

类型断言

let someValue: unknown = "hello";
let strLength: number = (someValue as string).length;
// 或者 <string>someValue .length(JSX 中不能用)

配置建议(tsconfig.json 最小配置)

{
  "compilerOptions": {
    "target": "ES2020",           // 编译目标
    "module": "commonjs",         // 模块系统
    "strict": true,               // 开启所有严格类型检查(强烈推荐)
    "esModuleInterop": true,      // 简化导入 commonjs 模块
    "skipLibCheck": true
  },
  "include": ["src/**/*"]
}

快速上手示例

// 假设你写一个简单的待办事项管理器
interface Todo {
  id: number;
  text: string;
  completed: boolean;
}

class TodoList {
  private todos: Todo[] = [];

  add(text: string): void {
    this.todos.push({
      id: Date.now(),
      text,
      completed: false,
    });
  }

  complete(id: number): void {
    const todo = this.todos.find(t => t.id === id);
    if (todo) todo.completed = true;
  }

  list(): Todo[] {
    return this.todos;
  }
}

const myList = new TodoList();
myList.add("学 TypeScript");
myList.add("写一篇教程");
myList.complete(myList.list()[0].id);
console.log(myList.list());

总结

TypeScript 的核心就是给 JS 加上类型。你不需要一开始就用所有高级特性,只需从 :类型 注解开始,逐步学习接口、泛型、类型守卫等。strict: true 会让你写出更可靠的代码。

学习路径建议
基础类型 → 函数 → 接口 → 类 → 泛型 → 高级类型(实用工具类型等)

现在就可以把 .js 文件改成 .ts,感受类型系统带来的安全感!