I have a question about Javascript/Typescript functions arguments and clean code. So I will use a simple example to illustrate my mean.
I created a React component with view property as props:
<Grid view="Horizontal" />
type PropsInterface = {
view: string
}
const Grid = ( { view }:PropsInterface )=>{
...
}
view can have several options. For example: "Horizontal", "Vertical" etc.
Question:
What is the best way to define view options so that I don't forget them or that other developers can easily understand?
Is the bottom method good? Are there better ways?
type PropsInterface = {
view: "Horizontal" | "Vertical"
}
Typescript has an Enum type -
enum ViewDirection {
Horizontal = "Horizontal",
Down = "Vertical",
}
From TypeScript Docs:
In modern TypeScript, you may not need an enum when an object with as const could suffice:
So you can do:
const ViewDirection = {
Horizontal = "Horizontal",
Down = "Vertical",
} as const;
VS String Type
If the values of the strings are subject to change then using a string-enum means only changing 1 string literal, whereas using a string-type means changing them everywhere they're used.
In layman terms you can change Horizontal = "Horizontal" to Horizontal = "H" without the need to change it everywhere when using a string enum.
More in depth here:
Difference between string enums and string literal types in TS