首页 > 解决方案 > 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

标签: typescript

解决方案


您只需要为每个参数提供一个类型和默认值。

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
}

推荐阅读