元素码农
基础
UML建模
数据结构
算法
设计模式
网络
TCP/IP协议
HTTPS安全机制
WebSocket实时通信
数据库
sqlite
postgresql
clickhouse
后端
rust
go
java
php
mysql
redis
mongodb
etcd
nats
zincsearch
前端
浏览器
javascript
typescript
vue3
react
游戏
unity
unreal
C++
C#
Lua
App
android
ios
flutter
react-native
安全
Web安全
测试
软件测试
自动化测试 - Playwright
人工智能
Python
langChain
langGraph
运维
linux
docker
工具
git
svn
🌞
🌙
目录
▶
TypeScript环境准备
安装与配置
第一个TS程序
编译流程解析
▶
基础类型系统
类型注解语法
原始类型定义
数组与元组
接口与对象
▶
高级类型系统
泛型编程
条件类型
映射类型
类型推断
类型保护
高级类型工具
▶
函数开发
函数类型声明
可选参数与默认值
箭头函数应用
函数重载
泛型函数
▶
类与面向对象
类的定义
继承与修饰符
存取器使用
抽象类与接口
泛型类与抽象类
访问修饰符与属性
▶
模块化开发
模块导入导出
类型声明文件
命名空间
模块解析策略
▶
工程实践
tsconfig详解
常见编译选项
项目构建配置
代码组织最佳实践
单元测试
调试技巧
▶
常见问题
类型错误处理
类型断言技巧
类型兼容性
版本迁移指南
发布时间:
2025-03-31 09:22
↑
☰
# 可选参数与默认值 TypeScript中的函数参数可以设置为可选的,也可以指定默认值。本文将详细介绍这些特性的使用方法和最佳实践。 ## 可选参数 ### 基本语法 ```typescript // 使用问号标记可选参数 function buildName(firstName: string, lastName?: string): string { if (lastName) { return `${firstName} ${lastName}`; } return firstName; } // 调用函数 console.log(buildName("John")); // "John" console.log(buildName("John", "Doe")); // "John Doe" ``` ### 多个可选参数 ```typescript function createUser( name: string, age?: number, email?: string ): object { return { name, ...(age && { age }), ...(email && { email }) }; } // 调用示例 console.log(createUser("John")); // { name: "John" } console.log(createUser("John", 25)); // { name: "John", age: 25 } console.log(createUser("John", 25, "john@example.com")); // { name: "John", age: 25, email: "john@example.com" } ``` ## 默认参数 ### 基本语法 ```typescript // 使用等号设置默认值 function greet(name: string, greeting: string = "Hello"): string { return `${greeting}, ${name}!`; } // 调用函数 console.log(greet("John")); // "Hello, John!" console.log(greet("John", "Hi")); // "Hi, John!" ``` ### 多个默认参数 ```typescript function createPoint( x: number = 0, y: number = 0, z: number = 0 ): { x: number; y: number; z: number } { return { x, y, z }; } // 调用示例 console.log(createPoint()); // { x: 0, y: 0, z: 0 } console.log(createPoint(1)); // { x: 1, y: 0, z: 0 } console.log(createPoint(1, 2)); // { x: 1, y: 2, z: 0 } console.log(createPoint(1, 2, 3)); // { x: 1, y: 2, z: 3 } ``` ## 可选参数与默认值的结合 ```typescript function processConfig( data: string, encoding: string = "utf-8", callback?: (error: Error | null, result: string) => void ): void { try { const result = `Processed ${data} with ${encoding} encoding`; if (callback) { callback(null, result); } } catch (error) { if (callback) { callback(error as Error, ""); } } } // 使用示例 processConfig("Hello"); processConfig("Hello", "ascii"); processConfig("Hello", "utf-8", (error, result) => { if (error) { console.error(error); } else { console.log(result); } }); ``` ## 参数解构 ```typescript // 使用解构的默认值 function printPerson({ name = "Anonymous", age = 0, email = "none" }: { name?: string; age?: number; email?: string; } = {}) { console.log(`Name: ${name}, Age: ${age}, Email: ${email}`); } // 调用示例 printPerson(); // Name: Anonymous, Age: 0, Email: none printPerson({ name: "John" }); // Name: John, Age: 0, Email: none printPerson({ name: "John", age: 25 }); // Name: John, Age: 25, Email: none ``` ## 最佳实践 1. **可选参数放在最后**: ```typescript // 好的实践 function createProfile(name: string, age?: number, bio?: string) { // ... } // 避免这样做 function createProfile(name?: string, age: number, bio?: string) { // 编译错误:必需参数不能位于可选参数后 } ``` 2. **合理使用默认值**: ```typescript // 好的实践 function request( url: string, method: string = "GET", timeout: number = 5000 ) { // ... } // 避免过度使用默认值 function complexFunction( a = 1, b = 2, c = 3, d = 4, e = 5 // 太多默认值可能导致函数难以理解 ) { // ... } ``` 3. **使用接口定义选项对象**: ```typescript interface RequestOptions { method?: string; timeout?: number; headers?: Record<string, string>; } function request(url: string, options: RequestOptions = {}) { const { method = "GET", timeout = 5000, headers = {} } = options; // ... } ``` ## 常见问题 1. **undefined与默认值**: ```typescript function example(value: string = "default") { console.log(value); } example(); // "default" example(undefined); // "default" example("test"); // "test" ``` 2. **null与默认值**: ```typescript function process(value: string | null = "default") { console.log(value); } process(); // "default" process(null); // null process("test"); // "test" ``` ## 下一步 掌握了可选参数和默认值后,你可以: 1. 学习函数重载 2. 探索泛型函数 3. 了解箭头函数 4. 实践函数式编程 通过合理使用可选参数和默认值,你可以创建更加灵活和易用的TypeScript函数。