Issue
I have and enum and two functions that returns different data types:
enum Figure {
Circle,
Square,
}
const getCircle = () => ({
figure: Figure.Circle,
radius: 1
})
const getSquare = () => ({
figure: Figure.Square,
width: 1
})
I want to have a union type AnyFigure
so that I can use circles and squares in combination. I can do so by defining both types:
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 }
This works fine, but I don't want to define return type of every "get figure" function (because in my actual code those are action creators that I use in React's useReducer hook, and there could be quite of few of them, each with different return type).
Thus I tried to use ReturnType instead:
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 }
What am I missing here? Thanks.
Solution
You can just use as const
on enum properties:
enum Figure {
Circle,
Square,
}
const getCircle = () => ({
figure: Figure.Circle as const,
radius: 1
})
const getSquare = () => ({
figure: Figure.Square as const,
width: 1
})
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 }
Answered By - Roberto Zvjerković
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.