TypeScript 是 JavaScript 的超集,由微软开发并开源。它在保留 JavaScript 灵活性的同时,引入了静态类型系统、接口、泛型等强大特性,让代码更健壮、可维护。无论你是在构建大型企业应用还是小型库,TypeScript 都能显著提升开发效率。本篇教程将用 50 分钟带你系统掌握 TypeScript 的核心知识,从环境搭建到高级类型,配合大量代码示例,助你快速入门。
初识 TypeScript
TypeScript 最终会被编译成纯净的 JavaScript,它提供了可选的静态类型检查、ES6+ 特性支持以及丰富的工具提示。
npm install -g typescript
// 编译一个 .ts 文件
tsc hello.ts
// 一个简单的 TypeScript 例子
function greet(name: string) {
return `Hello, ${name.toUpperCase()}!`;
}
console.log(greet('TypeScript'));
📦 源码 (.ts) → 编译器 (tsc) → 纯净 JS (.js) → 执行
基础类型
TypeScript 在 JavaScript 基础上增加了类型注解,让每个变量都“有据可循”。
let isDone: boolean = false;
let decimal: number = 42;
let color: string = "blue";
// 数组与元组
let list: number[] = [1,2,3];
let tuple: [string, number] = ["age", 30];
// 枚举
enum Direction { Up, Down, Left, Right }
let dir: Direction = Direction.Up;
// any、void、null、undefined
let notSure: any = 4;
function warn(): void { console.log("warning"); }
✔ 类型注解在编译时被擦除,无运行时开销。
接口 interface
接口用于定义对象的结构,是 TypeScript 的核心特性之一。
interface Person {
name: string;
age: number;
readonly id: number;
email?: string; // 可选
}
function greetPerson(p: Person) {
console.log(`Hello ${p.name}`);
}
// 函数类型接口
interface SearchFunc {
(source: string, sub: string): boolean;
}
接口可以扩展(extends),类型别名(type)更灵活。推荐优先使用接口描述对象。
interface Animal { name: string }
interface Bear extends Animal { honey: boolean }
类 Class
TypeScript 对 ES6 类进行了增强,增加了访问修饰符、抽象类等。
class Animal {
protected name: string;
constructor(name: string) { this.name = name; }
public move(distance: number) {
console.log(`${this.name} moved ${distance}m`);
}
}
// 抽象类
abstract class Department {
abstract printMeeting(): void;
}
private 仅在类内访问
protected 允许派生类访问
public 默认,任何地方可访问
函数进阶
TypeScript 可以精确描述函数的输入输出,支持重载、可选参数等。
function buildName(first: string, last?: string): string {
return last ? first + ' ' + last : first;
}
// 重载
function pickCard(x: { suit: string }): number;
function pickCard(x: number): { suit: string };
function pickCard(x: any): any { /* 实现 */ }
?: 可选 =默认值 ...rest
剩余参数示例:function sum(...nums: number[])
泛型 Generics
泛型让组件可以支持多种类型,同时保持类型安全。
function identity
// 泛型接口
interface GenericFn {
// 泛型类
class Box
content: T;
constructor(value: T) { this.content = value; }
}
function logging(arg: T): T {
console.log(arg.length); return arg; }
高级类型
联合类型、交叉类型、类型保护等让类型系统更灵活。
type Status = "success" | "error" | "loading";
type A = { a: number } & { b: string }; // 交叉
// 类型保护
function isString(x: any): x is string {
return typeof x === 'string';
}
模块与命名空间
TypeScript 支持 ES6 模块语法,也可以使用内部命名空间(老项目)。
export interface User { name: string; }
import { User } from './types';
// 默认导出
export default function() { }
📁 推荐使用 ES Module 方式,配合打包工具。
export import default
装饰器 (Decorator)
装饰器为类和类成员提供元编程能力,在 Angular / NestJS 中广泛使用。
function sealed(constructor: Function) {
Object.seal(constructor);
}
@sealed
class Greeter {
greet() { return "hello"; }
}
🔮 类装饰器、方法装饰器、属性装饰器、参数装饰器
tsconfig.json 详解
TypeScript 项目通过 tsconfig.json 管理编译选项。
"compilerOptions": {
"target": "ES2020",
"module": "commonjs",
"strict": true,
"outDir": "./dist",
"rootDir": "./src",
"esModuleInterop": true
},
"include": ["src/**/*"],
"exclude": ["node_modules"]
}
⚙️ 常用选项: strict 开启所有严格检查, noImplicitAny 禁止隐式 any
实用技巧与工具
使用 TypeScript 配合 VSCode 可以获得顶级智能提示;利用 typeof, keyof, in 关键字提高效率。
interface Person { name: string; age: number }
type PersonKeys = keyof Person; // "name" | "age"
// 映射类型
type ReadonlyPerson = { readonly [P in keyof Person]: Person[P] };
🚀 推荐工具:
TypeScript Playground, ts-node, @types/ 声明文件
从 JavaScript 迁移
逐步迁移:添加 // @ts-check,使用 JSDoc 类型注释,将 .js 改为 .ts 并修复错误。
/**
* @param {string} name
* @return {number}
*/
function getNameLength(name) { return name.length; }
✅ 先开启 allowJs 混合编译,再逐步重构。
📘 恭喜!你已掌握 TypeScript 核心知识。接下来可以在实际项目中大胆使用,配合框架(React/Vue/Angular)体验静态类型带来的安全感。