typescript - Typescript 中的解构和重命名可选参数
问题描述
我目前在 JS 中有以下内容,但想转换为 TS 并使两个参数都是可选的,同时保持重命名
const sortPositionAscending = ({ position: a }, { position: b }) => {
if (a < b) return -1
if (a > b) return 1
return 0
}
因为我会用它
const sortPositionDescending = (...args) =>
sortPositionAscending(...args) * -1
解决方案
您只需要为每个参数提供一个类型和默认值。
const sortPositionAscending = (
{ position: a }: { position: number } = { position: 0 },
{ position: b }: { position: number } = { position: 0 },
) => {
if (a < b) return -1
if (a > b) return 1
return 0
}
推荐阅读
- java - ExecutorService 和 Future 正在阻塞主线程
- ios - 使用 Audiokit v5 实现麦克风分析
- ios - UIBarButtonItem 隐藏元素和它占用的空间
- c# - Canvas ActualWidth 和 ActualHeight 以 MVVM 方式传入 ViewModel
- r - R - 查找第 2 组(对)的集群
- xamarin.forms - Xamarin.Forms 选中时禁用 Shell TabBar 字体缩放
- php - Laravel Eloquent 用于数据透视表,一个表有 2 个外键,另一个表有 1 个外键
- node.js - 如何使用 ejs 从 mongoDB 集合中提取文档,以便每个文档在浏览器上出现一次?
- python - 使用 asyncio.run() 时关闭 Asyncio 事件循环
- ms-access - 如何使用 MS Access 中的 SQL 查询将字段值增加 1