Appearance
TypeScript 速记表
基础语法
Hello World & 注释
// Hello Worldconsole.log("Hello, World!");// 单行注释/* 多行注释 *//** * JSDoc 注释 * @param name 用户名 * @returns 问候语 */输入输出
// 输出console.log("Hello, World!");console.error("Error message");console.warn("Warning");// 浏览器环境输入let name: string | null = prompt("Enter your name:");// Node.js 环境输入import * as readline from 'readline';const rl = readline.createInterface({ input: process.stdin, output: process.stdout});rl.question('Enter your name: ', (answer: string) => { console.log(`Hello, ${answer}`); rl.close();});变量与常量
声明方式
let mutable: number = 10const immutable: string = "hello"var oldStyle: any = 30 // 不推荐// 类型推导let x = 10 // 推导为 numberlet y = "hello" // 推导为 string作用域
// 全局作用域let globalVar: string = 'global'function example() { // 函数作用域 let funcVar: string = 'function' if (true) { // 块级作用域 let blockVar: string = 'block' const blockConst: string = 'const' }}数据类型
基本类型
let num: number = 42let str: string = "hello"let bool: boolean = truelet nul: null = nulllet undef: undefined = undefinedlet sym: symbol = Symbol('id')let big: bigint = 123n特殊类型
let anything: any = "anything"let nothing: void = undefinedlet never: never // 永不返回let unknown: unknown = 10 // 类型安全的 any数组与元组
let arr: number[] = [1, 2, 3]let arr2: Array<number> = [1, 2, 3]let tuple: [string, number] = ["age", 25]let tuple2: [string, number, boolean?] = ["name", 30]联合与交叉类型
// 联合类型let id: string | number = 123// 交叉类型type A = { name: string }type B = { age: number }type C = A & B // { name: string, age: number }字面量类型
let status: "success" | "error" | "pending"let direction: "left" | "right" | "up" | "down"let port: 3000 | 8080类型别名与接口
// 类型别名type User = { name: string age: number}// 接口interface IUser { name: string age: number greet(): void}运算符
基本运算符
// 算术+ - * / % **// 比较== != === !==> < >= <=// 逻辑&& || !// 赋值= += -= *= /= %=类型相关运算符
// 类型断言value as string<string>value// 非空断言user.name!// 可选链obj?.prop?.method?.()// 空值合并value ?? 'default'typeof / keyof
// typeofconst user = { name: "Alice", age: 25 }type UserType = typeof user// keyoftype UserKeys = keyof User // "name" | "age"字符串
字符串类型
let str: string = 'hello'let template: string = `Hello, ${name}` // 模板字面量类型type Greeting = `Hello, ${string}`type Route = `/api/${string}`字符串方法
str.lengthstr.charAt(0)str.indexOf('sub')str.includes('sub')str.startsWith('pre')str.endsWith('suf')str.slice(0, 5)str.split(' ')str.replace('old', 'new')str.toLowerCase()str.toUpperCase()str.trim()集合数据结构
数组类型
let numbers: number[] = [1, 2, 3]let strings: Array<string> = ["a", "b"]// 只读数组let readonly: readonly number[] = [1, 2, 3]let readonly2: ReadonlyArray<number> = [1, 2, 3]数组方法
arr.push(4)arr.pop()arr.shift()arr.unshift(0)arr.splice(1, 2)arr.slice(1, 3)arr.map(x => x * 2)arr.filter(x => x > 0)arr.reduce((acc, x) => acc + x, 0)arr.find(x => x > 5)arr.some(x => x > 5)arr.every(x => x > 0)Map 类型
let map: Map<string, number> = new Map()map.set('key', 100)map.get('key')map.has('key')map.delete('key')// Record 类型type StringMap = Record<string, number>let obj: StringMap = { a: 1, b: 2 }Set 类型
let set: Set<number> = new Set([1, 2, 3])set.add(4)set.has(1)set.delete(1)set.sizefor (const value of set) {}控制流
if / else
if (condition) { // 执行} else if (other) { // 执行} else { // 执行}const result = condition ? 'yes' : 'no'switch
switch (value) { case 1: console.log('one') break case 2: case 3: console.log('two or three') break default: console.log('other')}循环
for (let i = 0; i < 10; i++) {}for (const item of array) {}for (const key in object) {}while (condition) {}do {} while (condition)类型守卫
function isString(x: any): x is string { return typeof x === "string"}if (isString(value)) { // value 是 string 类型 console.log(value.toUpperCase())}函数
函数声明
function add(a: number, b: number): number { return a + b}const multiply = (a: number, b: number): number => a * bconst greet: (name: string) => string = (name) => { return `Hello, ${name}`}可选与默认参数
function greet(name: string, age?: number): string { return `Hello, ${name}`} function log(msg: string, prefix = "INFO"): void { console.log(`[${prefix}] ${msg}`)}剩余参数
function sum(...nums: number[]): number { return nums.reduce((acc, n) => acc + n, 0)}function format(template: string, ...args: any[]): string { return template}函数重载
function format(value: string): stringfunction format(value: number): stringfunction format(value: string | number): string { return String(value)}泛型函数
function identity<T>(arg: T): T { return arg}const result = identity<string>("hello")const result2 = identity(42) // 类型推导高级类型
泛型
interface Box<T> { value: T}class Container<T> { constructor(private value: T) {} getValue(): T { return this.value }}泛型约束
interface HasLength { length: number}function log<T extends HasLength>(arg: T): void { console.log(arg.length)}// 多重约束function merge<T extends object, U extends object>(a: T, b: U): T & U { return { ...a, ...b }}Utility Types
Partial<T> // 所有属性可选Required<T> // 所有属性必填Readonly<T> // 所有属性只读Pick<T, K> // 选择部分属性Omit<T, K> // 排除部分属性Record<K, T> // 键值对类型Exclude<T, U> // 从 T 中排除 UExtract<T, U> // 从 T 中提取 UNonNullable<T> // 排除 null 和 undefinedReturnType<T> // 函数返回类型Parameters<T> // 函数参数类型条件类型
type IsString<T> = T extends string ? true : falsetype NonNullable<T> = T extends null | undefined ? never : T// 分发条件类型type ToArray<T> = T extends any ? T[] : never映射类型
type Readonly<T> = { readonly [P in keyof T]: T[P]}type Optional<T> = { [P in keyof T]?: T[P]}type Getters<T> = { [P in keyof T as `get${Capitalize<string & P>}`]: () => T[P]}模板字面量类型
type HttpMethod = "GET" | "POST"type Route = "/api" | "/admin"type Endpoint = `${HttpMethod} ${Route}` type Getters<T> = { [K in keyof T as `get${Capitalize<string & K>}`]: () => T[K]}面向对象
类定义
class Person { private name: string protected age: number public readonly id: number constructor(name: string, age: number) { this.name = name this.age = age this.id = Date.now() } greet(): string { return `Hello, I'm ${this.name}` }}继承
class Student extends Person { constructor(name: string, age: number, public grade: string) { super(name, age) } study(): void { console.log('Studying...') }}抽象类
abstract class Animal { abstract makeSound(): void move(): void { console.log('Moving...') }}class Dog extends Animal { makeSound(): void { console.log('Woof!') }}接口
interface Drawable { draw(): void}interface Clickable { click(): void}class Button implements Drawable, Clickable { draw(): void {} click(): void {}}访问器
class User { private _name: string = "" get name(): string { return this._name } set name(value: string) { this._name = value.trim() }}泛型类
class Stack<T> { private items: T[] = [] push(item: T): void { this.items.push(item) } pop(): T | undefined { return this.items.pop() }}异步编程
Promise 类型
function fetchData(): Promise<string> { return new Promise((resolve, reject) => { resolve("data") })}const promise: Promise<number> = Promise.resolve(42)async/await
async function getData(): Promise<User> { try { const response = await fetch("/api/user") const data: User = await response.json() return data } catch (error) { throw new Error("Failed to fetch") }}泛型 Promise
async function request<T>(url: string): Promise<T> { const response = await fetch(url) return response.json()}const user = await request<User>("/api/user")错误处理
try/catch
try { throw new Error("Something went wrong")} catch (error) { if (error instanceof Error) { console.error(error.message) }} finally { console.log("Cleanup")}自定义错误
class ValidationError extends Error { constructor(message: string) { super(message) this.name = 'ValidationError' }}throw new ValidationError("Invalid input")模块
导入导出
// 导出export const PI = 3.14export function add(a: number, b: number) {}export default class User {}// 导入import User, { PI, add } from './module'import * as Utils from './utils'类型导入导出
export type UserType = { name: string}export interface IConfig { apiUrl: string}import type { UserType, IConfig } from './types'// 仅导入类型import { type User } from './user'命名空间
namespace Validation { export interface StringValidator { isValid(s: string): boolean } export class EmailValidator implements StringValidator { isValid(s: string): boolean { return s.includes("@") } }}装饰器
类装饰器
function sealed(constructor: Function) { Object.seal(constructor) Object.seal(constructor.prototype)}@sealedclass Greeter { greeting: string constructor(message: string) { this.greeting = message }}方法装饰器
function log(target: any, key: string, descriptor: PropertyDescriptor) { const original = descriptor.value descriptor.value = function(...args: any[]) { console.log(`Calling ${key}`) return original.apply(this, args) }} class Calculator { @log add(a: number, b: number): number { return a + b }}最佳实践
代码风格
// 使用接口而非类型别名定义对象形状interface User { name: string age: number}// 使用 const 断言const colors = ['red', 'blue'] as const// 避免 any,使用 unknownfunction process(value: unknown) { if (typeof value === 'string') {}}类型安全
// 使用严格模式{ "compilerOptions": { "strict": true, "noImplicitAny": true, "strictNullChecks": true }}// 使用类型守卫function isUser(obj: any): obj is User { return 'name' in obj && 'age' in obj}常见陷阱
// 避免类型断言滥用const value = someValue as any // 不好const value = someValue as SomeType // 谨慎使用// 注意可选链和空值合并obj?.prop // 可能是 undefinedobj ?? 'default' // 只处理 null/undefined工具链
编译器配置
// tsconfig.json{ "compilerOptions": { "target": "ES2020", "module": "ESNext", "strict": true, "esModuleInterop": true, "skipLibCheck": true, "forceConsistentCasingInFileNames": true }}构建工具
# TypeScript 编译器tsctsc --watch# Webpack with ts-loaderwebpack --mode production# Vite (原生支持)vite build# esbuildesbuild src/index.ts --bundle类型声明
# 安装类型声明npm install --save-dev @types/nodenpm install --save-dev @types/react# 生成声明文件tsc --declaration