| Java | TypeScript | 说明 |
|---|---|---|
String name = "hello" | const name: string = "hello" | 类型在后,const ≈ final |
int age = 25 | let age = 25 | let = 可变变量 |
List<String> | string[] | 数组用 [] |
Map<String, Object> | Record<string, any> | any ≈ Object |
interface User {...} | interface User {...} | 完全一样 |
@Nullable String name | name?: string | ? = 可选 |
// 1. 解构赋值 — 从对象里一次取出多个属性 const { name, price } = product // 相当于 const name = product.name const [first, second] = [1, 2, 3] // 2. 展开运算符 — 合并对象/数组 const merged = { ...defaults, ...custom } // 后面覆盖前面 const all = [...oldItems, newItem] // 3. 可选链 — 安全访问,不用判空 const city = user?.address?.city // 有 null → undefined,不抛异常 // 4. 箭头函数 — 更短 items.map(item => item.name) // 单行省略 return items.filter(item => item.price > 100) // 5. async/await — 和 Java 21 虚拟线程类似 const data = await fetch('/api/products')
// interface — 定义对象结构(和 Java 一样) interface Product { id: string name: string price: number description?: string // ? = 可选 } // type — 联合类型(Java 没有) type Status = 'pending' | 'confirmed' | 'shipped' // Status 类型变量只能赋这三个值之一 // 函数类型 function getTotal(items: OrderItem[]): number { return items.reduce((sum, item) => sum + item.price * item.quantity, 0) }