TypeScript 入门完全指南 – JavaScript 开发者的进阶之路

为什么需要 TypeScript

  • 类型安全 – 编译时发现错误,而不是运行时
  • 更好的 IDE 支持 – 自动补全、跳转、重构
  • 代码文档化 – 类型即文档
  • 大型项目必备 – Angular、Vue 3 都用 TS

安装

# 全局安装
npm install -g typescript

# 项目安装
npm install -D typescript

# 编译
tsc hello.ts

基础类型

// 基础类型
let name: string = 'John'
let age: number = 25
let isActive: boolean = true

// 数组
let nums: number[] = [1, 2, 3]
let names: Array = ['a', 'b']

// 元组
let tuple: [string, number] = ['hello', 42]

// 枚举
enum Status { Active, Inactive }
let s: Status = Status.Active

// any(避免使用)
let anyValue: any = 'any'

// void(无返回值)
function log(): void {
  console.log('hello')
}

// null 和 undefined
let n: null = null
let u: undefined = undefined

接口

// 定义对象类型
interface User {
  id: number
  name: string
  email?: string  // 可选属性
  readonly created: Date  // 只读属性
}

const user: User = {
  id: 1,
  name: 'John',
  created: new Date()
}

// 接口继承
interface Admin extends User {
  role: string
}

类型别名

// type 别名
type ID = number | string
type Point = { x: number, y: number }

// 联合类型
type Result = Success | Error

interface Success {
  ok: true
  data: any
}

interface Error {
  ok: false
  message: string
}

函数类型

// 函数声明
function add(a: number, b: number): number {
  return a + b
}

// 函数类型
type Callback = (error: Error, result: string) => void

// 可选参数和默认参数
function greet(name: string, greeting?: string = 'Hello') {
  return `${greeting}, ${name}!`
}

泛型

// 泛型函数
function identity(arg: T): T {
  return arg
}

// 泛型接口
interface ApiResponse {
  data: T
  status: number
}

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

function logLength(arg: T): void {
  console.log(arg.length)
}

class User {
  private id: number
  public name: string
  protected email: string
  
  constructor(id: number, name: string, email: string) {
    this.id = id
    this.name = name
    this.email = email
  }
  
  greet(): void {
    console.log(`Hi, I'm ${this.name}`)
  }
}

class Admin extends User {
  role: string
  
  constructor(id: number, name: string, email: string, role: string) {
    super(id, name, email)
    this.role = role
  }
}

类型守卫

// typeof
if (typeof value === 'string') {
  console.log(value.toUpperCase())
}

// instanceof
if (obj instanceof Error) {
  console.log(obj.message)
}

// 自定义类型守卫
function isString(value: any): value is string {
  return typeof value === 'string'
}

常用配置

// tsconfig.json
{
  "compilerOptions": {
    "target": "ES2020",
    "module": "ESNext",
    "strict": true,
    "esModuleInterop": true,
    "skipLibCheck": true,
    "outDir": "./dist",
    "rootDir": "./src"
  }
}

总结

TypeScript 是现代前端开发的必备技能。它的类型系统可以显著减少 bug,提高代码质量和开发效率。建议所有 JavaScript 项目都迁移到 TypeScript。

Comments

No comments yet. Why don’t you start the discussion?

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注