'TypeScript array square bracket syntax with type values
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);
Solution 1:[1]
("top", "bottom") is using the comma operator - that expression is equivalent to "bottom", which is not what you want (and on which includes happens to work because it's a string method as well as an array method, but it's not the logic you're looking for).
Put square brackets around the array you're searching, then assert that it's Array<Placement> with as, then call .includes on the whole result.
const isHorizontal = (placement: Placement): boolean => (["top", "bottom"] as Array<Placement>).includes(placement);
You might consider avoiding using angle bracket syntax and using as instead to avoid ambiguity with JSX - eg, use expression as string instead of <string>expression.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | CertainPerformance |
