TypeScript

JavaScript 的超集 - 带类型的 JavaScript

📝 基础类型

类型声明

// 基础类型
let count: number = 42
let name: string = "TypeScript"
let isActive: boolean = true

// 数组
let numbers: number[] = [1, 2, 3]
let names: Array = ["A", "B"]

// 元组
let user: [string, number] = ["Alice", 25]

// 枚举
enum Color {
  Red = "red",
  Green = "green",
  Blue = "blue"
}

// 任意类型
let anything: any = 4
anything = "four"

运行演示

类型检查结果:

数字: 42

字符串: TypeScript

布尔值: true

🔷 接口(Interface)

接口定义

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

interface Admin extends User {
  role: 'admin' | 'super-admin'
}

function createUser(user: User): User {
  return user
}

const admin: Admin = {
  id: 1,
  name: "Alice",
  age: 25,
  role: "admin"
}

函数接口

interface Calculator {
  (a: number, b: number): number
}

const add: Calculator = (a, b) => a + b
const multiply: Calculator = (a, b) => a * b

interface Config {
  name: string
  version: string
  config(options: Config): void
}

const appConfig: Config = {
  name: "MyApp",
  version: "1.0.0",
  config(options) {
    console.log(options)
  }
}

🏛️ 类(Class)

类的定义与继承

class Person {
  name: string
  age: number

  constructor(name: string, age: number) {
    this.name = name
    this.age = age
  }

  greet(): string {
    return `Hello, I'm ${this.name}`
  }
}

class Employee extends Person {
  employeeId: number
  department: string

  constructor(
    name: string,
    age: number,
    id: number,
    dept: string
  ) {
    super(name, age)
    this.employeeId = id
    this.department = dept
  }

  greet(): string {
    return `${super.greet()}, ID: ${this.employeeId}`
  }

  getInfo(): string {
    return `${this.name}, ${this.age}, Dept: ${this.department}`
  }
}

创建实例

继承演示

⚡ 泛型(Generic)

泛型函数

function identity<T>(arg: T): T {
  return arg
}

let stringResult = identity<string>("hello")
let numberResult = identity<number>(42)

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

function loggingIdentity<T extends Lengthwise>(arg: T): T {
  console.log(arg.length)
  return arg
}

泛型类

class GenericNumber<T> {
  value: T
  constructor(value: T) {
    this.value = value
  }

  add(another: T): T {
    return this.value + another
  }
}

let numberGeneric = new GenericNumber<number>(10)
let stringGeneric = new GenericNumber<string>("Hello ")

泛型应用演示

数组泛型

对象泛型

函数泛型

🎯 高级类型

联合类型 (Union)

let id: number | string
id = "abc123"
id = 123

function printId(id: number | string) {
  console.log(id)
}

交叉类型 (Intersection)

interface Person {
  name: string
}

interface Employee {
  employeeId: number
}

type PersonEmployee = Person & Employee