TypeScript 核心语法速查

一、基础类型

1. 原始类型

```typescript

// 基本类型注解

const name: string = '张三'

const age: number = 25

const isActive: boolean = true

const nothing: null = null

const notDefined: undefined = undefined

// Symbol (ES6+)

const sym: symbol = Symbol('id')

// BigInt (ES2020+)

const big: bigint = 100n

```

2. 数组和元组

```typescript

// 数组

const numbers: number[] = [1, 2, 3]

const strings: Array<string> = ['a', 'b', 'c']

// 只读数组

const readonlyArr: readonly number[] = [1, 2, 3]

// readonlyArr[0] = 4 // 错误:只读

// 元组(固定长度和类型)

const tuple: [string, number] = ['张三', 25]

tuple[0] = '李四' // ✅

// tuple[0] = 30 // ❌ 类型错误

// tuple[2] = true // ❌ 越界错误

// 可选元素的元组

const optionalTuple: [string, number?] = ['张三'] // 第二个元素可选

// 带标签的元组(更易读)

const labeledTuple: [name: string, age: number] = ['张三', 25]

```

3. 特殊类型

```typescript

// any - 关闭类型检查(避免使用)

let anything: any = 'hello'

anything = 42

anything = true

// unknown - 类型安全的any

let uncertain: unknown = 'hello'

// uncertain.toUpperCase() // ❌ 需要类型检查

if (typeof uncertain === 'string') {

uncertain.toUpperCase() // ✅

}

// void - 没有返回值

function log(message: string): void {

console.log(message)

}

// never - 永远不会返回

function throwError(message: string): never {

throw new Error(message)

}

function infiniteLoop(): never {

while (true) {}

}

```

二、类型别名和接口

1. 类型别名(Type Alias)

```typescript

// 基础类型别名

type ID = string | number

type Point = {

x: number

y: number

}

// 函数类型

type Callback = (data: string) => void

// 联合类型

type Status = 'pending' | 'success' | 'error'

// 交叉类型

type Person = {

name: string

age: number

}

type Employee = Person & {

employeeId: string

department: string

}

// 工具类型(后面详细讲)

type PartialPerson = Partial<Person>

type ReadonlyPerson = Readonly<Person>

```

2. 接口(Interface)

```typescript

// 基础接口

interface User {

readonly id: string // 只读属性

name: string

age: number

email?: string // 可选属性

key: string\]: any // 索引签名 } // 函数接口 interface SearchFunc { (source: string, subString: string): boolean } // 可索引接口 interface StringArray { \[index: number\]: string } // 类接口 interface ClockInterface { currentTime: Date setTime(d: Date): void } // 接口继承 interface Employee extends User { employeeId: string department: string } // 接口合并(声明合并) interface Box { height: number } interface Box { width: number } // 最终 Box 有 height 和 width 两个属性 \`\`\` ### 3. Type vs Interface \`\`\`typescript // 相同点:都可以描述对象结构 type UserType = { name: string age: number } interface UserInterface { name: string age: number } // 不同点: // 1. interface 可以合并 interface User { name: string } interface User { age: number } // 合并 // type 不能重复声明 type User = { name: string } // type User = { age: number } // ❌ 错误 // 2. interface 可以 extends interface Admin extends User { role: string } // type 使用交叉类型 type Admin = User \& { role: string } // 3. type 更灵活(联合类型、元组等) type Status = 'success' \| 'error' // 联合类型 type Pair = \[string, number\] // 元组类型 // 实践建议:能用 interface 就用 interface,需要联合类型时用 type \`\`\` ## 三、函数 ### 1. 函数类型 \`\`\`typescript // 函数声明 function add(x: number, y: number): number { return x + y } // 函数表达式 const multiply: (x: number, y: number) =\> number = function(x, y) { return x \* y } // 箭头函数 const divide = (x: number, y: number): number =\> x / y // 可选参数(必须在必选参数后面) function greet(name: string, greeting?: string): string { return \`${greeting \|\| 'Hello'}, ${name}\` } // 默认参数 function createUser(name: string, age: number = 18): User { return { name, age } } // 剩余参数 function sum(...numbers: number\[\]): number { return numbers.reduce((a, b) =\> a + b, 0) } // 函数重载(多个签名) function processData(data: string): string function processData(data: number): number function processData(data: string \| number): string \| number { if (typeof data === 'string') { return data.toUpperCase() } return data \* 2 } // this 类型 interface Card { suit: string card: number showCard(this: Card): () =\> string } const card: Card = { suit: 'spades', card: 1, showCard: function(this: Card) { return () =\> \`${this.suit} ${this.card}\` } } \`\`\` ## 四、类 ### 1. 基础类 \`\`\`typescript class Person { // 属性 name: string protected age: number // 受保护的(子类可访问) private id: string // 私有的(仅类内部) readonly createdAt: Date // 只读 // 静态属性 static species = 'Human' // 构造函数 constructor(name: string, age: number) { this.name = name this.age = age this.id = Math.random().toString() this.createdAt = new Date() } // 方法 greet(): string { return \`Hello, I'm ${this.name}\` } // 存取器(getter/setter) get birthYear(): number { return new Date().getFullYear() - this.age } set birthYear(year: number) { this.age = new Date().getFullYear() - year } // 静态方法 static isPerson(obj: any): boolean { return obj instanceof Person } } // 使用 const person = new Person('张三', 25) console.log(person.greet()) console.log(Person.species) \`\`\` ### 2. 继承 \`\`\`typescript class Employee extends Person { // 新增属性 employeeId: string department: string constructor( name: string, age: number, employeeId: string, department: string ) { super(name, age) // 调用父类构造函数 this.employeeId = employeeId this.department = department } // 方法重写 override greet(): string { return \`${super.greet()}, I work in ${this.department}\` } // 新增方法 work(): string { return 'Working...' } } \`\`\` ### 3. 抽象类 \`\`\`typescript abstract class Animal { // 抽象属性 abstract name: string // 抽象方法(必须在子类实现) abstract makeSound(): void // 具体方法 move(): void { console.log('Moving...') } } class Dog extends Animal { name = 'Dog' makeSound(): void { console.log('Woof! Woof!') } } // const animal = new Animal() // ❌ 错误:抽象类不能实例化 const dog = new Dog() // ✅ \`\`\` ### 4. 接口实现 \`\`\`typescript interface Logger { log(message: string): void error(message: string): void } class ConsoleLogger implements Logger { log(message: string): void { console.log(\`\[LOG\] ${message}\`) } error(message: string): void { console.error(\`\[ERROR\] ${message}\`) } } // 实现多个接口 interface Serializable { serialize(): string } class User implements Logger, Serializable { name: string log(message: string): void { console.log(message) } error(message: string): void { console.error(message) } serialize(): string { return JSON.stringify(this) } } \`\`\` ## 五、泛型 ### 1. 基础泛型 \`\`\`typescript // 泛型函数 function identity\(arg: T): T { return arg } const output = identity\('hello') const output2 = identity(42) // 类型推断 // 泛型接口 interface GenericIdentityFn\ { (arg: T): T } // 泛型类 class GenericNumber\ { zeroValue: T add: (x: T, y: T) =\> T constructor(zeroValue: T, add: (x: T, y: T) =\> T) { this.zeroValue = zeroValue this.add = add } } const myNumber = new GenericNumber\(0, (x, y) =\> x + y) \`\`\` ### 2. 泛型约束 \`\`\`typescript // 基础约束 interface Lengthwise { length: number } function loggingIdentity\(arg: T): T { console.log(arg.length) return arg } // 使用 keyof 约束 function getProperty\(obj: T, key: K): T\[K\] { return obj\[key

}

const person = { name: '张三', age: 25 }

getProperty(person, 'name') // ✅

// getProperty(person, 'gender') // ❌ 错误

// 使用类约束

class Animal {

name: string

}

class Dog extends Animal {

breed: string

}

function createInstance<T extends Animal>(c: new () => T): T {

return new c()

}

createInstance(Dog) // ✅

// createInstance(String) // ❌ 错误

```

3. 泛型工具

```typescript

// 条件类型

type IsString<T> = T extends string ? 'yes' : 'no'

type Result1 = IsString<string> // 'yes'

type Result2 = IsString<number> // 'no'

// 推断类型

type ReturnType<T> = T extends (...args: any[]) => infer R ? R : any

type FuncReturn = ReturnType<() => string> // string

// 映射类型

type Optional<T> = {

P in keyof T\]?: T\[P

}

type Readonly<T> = {

readonly [P in keyof T]: T[P]

}

```

六、工具类型

1. 常用工具类型

```typescript

// Partial<T> - 所有属性变为可选

interface User {

name: string

age: number

}

type PartialUser = Partial<User>

// 相当于 { name?: string; age?: number }

// Required<T> - 所有属性变为必选

type RequiredUser = Required<PartialUser>

// 相当于 { name: string; age: number }

// Readonly<T> - 所有属性变为只读

type ReadonlyUser = Readonly<User>

// 相当于 { readonly name: string; readonly age: number }

// Record<K, T> - 创建记录类型

type UserRecord = Record<string, User>

// 相当于 { [key: string]: User }

// Pick<T, K> - 选择部分属性

type UserName = Pick<User, 'name'>

// 相当于 { name: string }

// Omit<T, K> - 排除部分属性

type UserWithoutAge = Omit<User, 'age'>

// 相当于 { name: string }

// Exclude<T, U> - 从T中排除U

type T0 = Exclude<"a" | "b" | "c", "a"> // "b" | "c"

// Extract<T, U> - 从T中提取U

type T1 = Extract<"a" | "b" | "c", "a" | "f"> // "a"

// NonNullable<T> - 排除null和undefined

type T2 = NonNullable<string | number | null | undefined> // string | number

// Parameters<T> - 获取函数参数类型

type T3 = Parameters<(a: string, b: number) => void> // [string, number]

// ReturnType<T> - 获取函数返回类型

type T4 = ReturnType<() => string> // string

// ConstructorParameters<T> - 获取构造函数参数类型

type T5 = ConstructorParameters<typeof User> // [name: string, age: number]

// InstanceType<T> - 获取实例类型

type T6 = InstanceType<typeof User> // User

```

2. 自定义工具类型

```typescript

// 移除所有可选修饰符

type Concrete<T> = {

P in keyof T\]-?: T\[P

}

// 移除所有只读修饰符

type Mutable<T> = {

-readonly [P in keyof T]: T[P]

}

// 获取函数参数类型

type FirstParam<T> = T extends (first: infer F, ...args: any[]) => any ? F : never

// 获取对象的值类型

type ValueOf<T> = T[keyof T]

// 深度只读

type DeepReadonly<T> = {

readonly [P in keyof T]: T[P] extends object ? DeepReadonly<T[P]> : T[P]

}

```

七、高级类型

1. 条件类型

```typescript

// 基础条件类型

type TypeName<T> =

T extends string ? 'string' :

T extends number ? 'number' :

T extends boolean ? 'boolean' :

T extends undefined ? 'undefined' :

T extends Function ? 'function' :

'object'

// 分布式条件类型

type Distributed<T> = T extends any ? T[] : never

type Result = Distributed<string | number> // string[] | number[]

// 过滤类型

type Filter<T, U> = T extends U ? T : never

type Filtered = Filter<string | number | boolean, string | number> // string | number

```

2. 模板字面量类型

```typescript

type World = "world"

type Greeting = `hello ${World}` // "hello world"

// 联合类型会组合所有可能

type Color = "red" | "blue"

type Quantity = "light" | "dark"

type ColorQuantity = `{Quantity}-{Color}`

// "light-red" | "light-blue" | "dark-red" | "dark-blue"

// 工具类型

type EventName<T extends string> = `${T}Changed`

type Concat<S1 extends string, S2 extends string> = `{S1}{S2}`

type Uppercase<S extends string> = `${Uppercase<S>}`

```

3. 映射类型修饰符

```typescript

// 添加修饰符

type AddOptional<T> = {

P in keyof T\]?: T\[P

}

type AddReadonly<T> = {

readonly [P in keyof T]: T[P]

}

// 移除修饰符

type RemoveOptional<T> = {

P in keyof T\]-?: T\[P

}

type RemoveReadonly<T> = {

-readonly [P in keyof T]: T[P]

}

// 键重映射

type Getters<T> = {

P in keyof T as \`get${Capitalize\}\`\]: () =\> T\[P

}

type RemoveKindField<T> = {

P in keyof T as Exclude\\]: T\[P

}

```

八、模块和命名空间

1. 模块

```typescript

// 导出(export.ts)

export const name = '张三' // 命名导出

export default function add(a: number, b: number): number { // 默认导出

return a + b

}

export type { User } // 导出类型

export interface Person { // 导出接口

name: string

}

// 导入(import.ts)

import add, { name, type User } from './export'

import * as utils from './export' // 全部导入

import type { Person } from './export' // 仅导入类型

// 重新导出

export { name } from './export'

export { default as AddFunction } from './export'

```

2. 命名空间(尽量避免使用,用模块替代)

```typescript

namespace Validation {

export interface StringValidator {

isAcceptable(s: string): boolean

}

export class LettersOnlyValidator implements StringValidator {

isAcceptable(s: string): boolean {

return /^[A-Za-z]+$/.test(s)

}

}

}

// 使用

let validator: Validation.StringValidator = new Validation.LettersOnlyValidator()

```

九、装饰器(实验性功能)

```typescript

// 类装饰器

function sealed(constructor: Function) {

Object.seal(constructor)

Object.seal(constructor.prototype)

}

// 方法装饰器

function enumerable(value: boolean) {

return function (target: any, propertyKey: string, descriptor: PropertyDescriptor) {

descriptor.enumerable = value

}

}

// 属性装饰器

function format(formatString: string) {

return function (target: any, propertyKey: string) {

// 在元数据中存储格式信息

}

}

// 参数装饰器

function validate(target: any, propertyKey: string, parameterIndex: number) {

// 验证参数

}

// 使用装饰器

@sealed

class Greeter {

@format("Hello, %s")

greeting: string

constructor(message: string) {

this.greeting = message

}

@enumerable(false)

greet(@validate name: string) {

return `{this.greeting}, {name}`

}

}

```

十、配置和实用技巧

1. tsconfig.json 核心配置

```json

{

"compilerOptions": {

/* 基本选项 */

"target": "ES2020", // 编译目标

"module": "ESNext", // 模块系统

"lib": ["ES2020", "DOM"], // 包含的库文件

"outDir": "./dist", // 输出目录

/* 类型检查 */

"strict": true, // 启用所有严格检查

"noImplicitAny": true, // 禁止隐式any

"strictNullChecks": true, // 严格空值检查

"strictFunctionTypes": true, // 严格函数类型检查

/* 模块解析 */

"moduleResolution": "node", // 模块解析策略

"baseUrl": "./", // 基础路径

"paths": { // 路径映射

"@/*": ["src/*"]

},

/* 其他 */

"esModuleInterop": true, // 兼容CommonJS和ES模块

"skipLibCheck": true, // 跳过库文件检查

"forceConsistentCasingInFileNames": true,

/* 实验性功能 */

"experimentalDecorators": true, // 启用装饰器

"emitDecoratorMetadata": true, // 发出装饰器元数据

"useDefineForClassFields": true // 使用ES类字段

},

"include": ["src/**/*"], // 包含的文件

"exclude": ["node_modules", "dist"] // 排除的文件

}

```

2. 实用技巧

```typescript

// 1. 类型断言

const value: any = 'hello'

const length = (value as string).length // 方式1

const length2 = (<string>value).length // 方式2(JSX中不能用)

// 2. 非空断言(谨慎使用)

function getValue(): string | undefined {

return Math.random() > 0.5 ? 'hello' : undefined

}

const value = getValue()!

value.toUpperCase() // 运行时可能出错

// 3. 双重断言

const value2: any = 'hello'

const element = value2 as unknown as HTMLElement

// 4. const 断言

const colors = ['red', 'green', 'blue'] as const

// 类型为:readonly ["red", "green", "blue"]

// 5. 使用 satisfies 操作符(TypeScript 4.9+)

const user = {

name: '张三',

age: 25

} satisfies { name: string; age: number }

// 类型检查但不改变推断类型

```

3. 类型守卫

```typescript

// typeof 守卫

function isString(value: any): value is string {

return typeof value === 'string'

}

// instanceof 守卫

class Bird {

fly() {

console.log('flying')

}

}

class Fish {

swim() {

console.log('swimming')

}

}

function move(animal: Bird | Fish) {

if (animal instanceof Bird) {

animal.fly()

} else {

animal.swim()

}

}

// in 操作符守卫

interface Cat {

meow(): void

}

interface Dog {

bark(): void

}

function makeSound(pet: Cat | Dog) {

if ('meow' in pet) {

pet.meow()

} else {

pet.bark()

}

}

// 自定义类型守卫

interface User {

name: string

email?: string

}

function isUser(obj: any): obj is User {

return obj && typeof obj.name === 'string'

}

```


**快速记忆要点:**

  1. **类型安全**:优先使用具体类型,避免使用 `any`

  2. **接口 vs 类型别名**:对象结构用 `interface`,联合类型用 `type`

  3. **泛型**:写可复用的类型安全代码

  4. **工具类型**:利用内置工具类型简化代码

  5. **严格模式**:始终开启 `strict: true`

  6. **类型推断**:让 TypeScript 推断类型,只在必要时显式注解

  7. **类型守卫**:使用类型守卫缩小类型范围

  8. **模块化**:使用 ES 模块,避免命名空间

**常用快捷键:**

  • VS Code 中悬停查看类型

  • `Ctrl + .` 快速修复

  • `F12` 跳转到定义

  • `Ctrl + Shift + P` -> "TypeScript: 转到项目配置"

相关推荐
家里有只小肥猫2 小时前
uniApp下拉渐变头部 拿来即用
前端·javascript·uni-app
一起养小猫2 小时前
Flutter for OpenHarmony 实战:科学计算器完整开发指南
android·前端·flutter·游戏·harmonyos
Jinuss2 小时前
源码分析之React中Scheduler调度器的任务优先级
前端·react.js·前端框架
波波0072 小时前
每日一题:在 .NET 中遍历集合(如 List<T>、数组、字典)的过程中进行增删改查会不会有影响?可能引发哪些问题?实际开发中应如何避免?
前端·list
念念不忘 必有回响2 小时前
码云流水线前端资源传输至目标服务器
运维·服务器·前端
我是伪码农2 小时前
Vue 2.2
前端·javascript·vue.js
●VON2 小时前
React Native for OpenHarmony:深入剖析 Switch 组件的状态绑定、无障碍与样式定制
javascript·学习·react native·react.js·von
时光追逐者2 小时前
一个基于 .NET + Vue 实现的通用权限管理平台(RBAC模式),前后端分离模式,开箱即用!
前端·vue.js·c#·.net·.net core
Aotman_2 小时前
Vue el-table 表尾合计行
前端·javascript·vue.js·elementui·前端框架·ecmascript