【发布时间】:2022-01-09 17:37:51
【问题描述】:
我有和枚举以及返回不同数据类型的两个函数:
enum Figure {
Circle,
Square,
}
const getCircle = () => ({
figure: Figure.Circle,
radius: 1
})
const getSquare = () => ({
figure: Figure.Square,
width: 1
})
我想要一个联合类型AnyFigure,这样我就可以组合使用圆形和正方形。我可以通过定义这两种类型来做到这一点:
type CircleType = {
figure: Figure.Circle,
radius: number
}
type SquareType = {
figure: Figure.Square,
width: number
}
type AnyFigure = CircleType | SquareType
// this throws compiler error because circles doesn't have width, which is great
const figure: AnyFigure = { figure: Figure.Circle, width: 4 }
这很好用,但我不想定义每个“get figure”函数的返回类型(因为在我的实际代码中,这些是我在 React 的 useReducer 钩子中使用的动作创建者,并且可能很少它们,每个都有不同的返回类型)。
因此我尝试使用 ReturnType:
type AnyFigureFromFuncs = ReturnType<typeof getCircle> | ReturnType<typeof getSquare>
// this doesn't throw compile errors, tested on TS 4.5.2
const figure: AnyFigureFromFuncs = { figure: Figure.Circle, width: 4 }
我在这里缺少什么?谢谢。
【问题讨论】:
标签: javascript typescript types union-types