Home > Enterprise >  TypeScript array square bracket syntax with type values
TypeScript array square bracket syntax with type values

Time:02-22

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);

CodePudding user response:

("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.

CodePudding user response:

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);
  • Related