2019-10-12
|~2 min read
|342 words
Working on a component that receives a status
prop where the status are defined by an enum (I’m working in Typescript).
The problem arose when a child component required a value for status
. Here’s a simplified illustration of what I’m talking about:
export enum StatusTypes {
INCOMPLETE = "INCOMPLETE",
ERROR = "ERROR",
COMPLETE = "COMPLETE",
}
export interface IStep {
id: string
status?: StatusTypes
}
const Step = (props: IStep) => {
/* … */
return <ChildComponent status={status} />
}
In normal circumstances, this could be simplified and we could get rid of the IStep
interface altogether.1
export enum StatusTypes {
INCOMPLETE = "INCOMPLETE",
ERROR = "ERROR",
COMPLETE = "COMPLETE",
}
export interface IStep {
id: string
status?: StatusTypes
}
const Step = ({ id: string, status: StatusTypes = StatusTypes.INCOMPLETE }) => {
/* … */
return <ChildComponent status={status} />
}
This is the best way to set a default to an Enum. Very explicitly, it’s occurring within the function signature, which is exactly where a default is assigned.
Two complicating factors:
status
was actually set within an array of elements that was being passed to the component at the top level. I.e., there’s another level above this and we get to step only after mapping over the steps.Okay, so a default value in the signature isn’t tenable, or at least not attractive. What about through destructuring?
That’s exactly what I did.
interface IMenu {
steps: IStep[]
}
const Step = (props: IStep) => {
const { step /* ... */ } = props
const { id, status = StepStatusTypes.INCOMPLETE } = step
/*...*/
}
The important part is that you can’t just set step.status
to "INCOMPLETE"
because that’s a string, and Typescript will yell.
Hi there and thanks for reading! My name's Stephen. I live in Chicago with my wife, Kate, and dog, Finn. Want more? See about and get in touch!