1

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

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

Comments

1

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

1 Comment

Thanks for the answer! I’m glad you pointed out the pitfall of the type assertion’s inability to future proof changes to the type. Because of this case, the intermediate variable provides value when using square bracket syntax.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.