Is it possible to write "isHoritzontal" using square bracket array syntax AND WITHOUT a variable assignment? I see it's possible with a variable assignment (ie. const a: Placement[] = ["top", "bottom"]
) but I'd like to know if it can be done in a single line of code like with Array<Placement>
as shown below.
type Placement = "top" | "bottom" | "left" | "right";
const isHorizontal = (placement: Placement): boolean =>
Array<Placement>("top", "bottom").includes(placement);
You would need to do this:
type Placement = "top" | "bottom" | "left" | "right";
const isHorizontal = (placement: Placement): boolean =>
(["top", "bottom"] as Placement[]).includes(placement);
However, I recommend using an intermediate variable with an explicit type to avoid bugs since a type assertion would allow your code to compile even if the array contains invalid strings. For example, if you later update the Placement
type, TypeScript will not complain about this code, even though it's no longer correct logically:
type Placement = "up" | "down" | "left" | "right";
const isHorizontal = (placement: Placement): boolean =>
(["top", "bottom"] as Placement[]).includes(placement);