带有类型值的 TypeScript 数组方括号语法

TypeScript array square bracket syntax with type values

是否可以使用方括号数组语法且不进行变量赋值来编写“isHoritzontal”?我看到变量赋值是可能的(即 const a: Placement[] = ["top", "bottom"]),但我想知道它是否可以在一行代码中完成,如下所示 Array<Placement>

type Placement = "top" | "bottom" | "left" | "right";

const isHorizontal = (placement: Placement): boolean =>
  Array<Placement>("top", "bottom").includes(placement);

("top", "bottom") 正在使用逗号运算符 - 该表达式等效于 "bottom",这不是您想要的(并且 includes 恰好可以工作,因为它是一个字符串方法以及数组方法,但这不是您要查找的逻辑)。

将要搜索的数组放在方括号中,然后断言它是 Array<Placement>as,然后对整个结果调用 .includes

const isHorizontal = (placement: Placement): boolean => (["top", "bottom"] as Array<Placement>).includes(placement);

您可以考虑避免使用尖括号语法并使用 as 来避免与 JSX 的歧义——例如,使用 expression as string 而不是 <string>expression

您需要这样做:

type Placement = "top" | "bottom" | "left" | "right";

const isHorizontal = (placement: Placement): boolean =>
  (["top", "bottom"] as Placement[]).includes(placement);

但是,我建议使用具有显式类型的中间变量以避免错误,因为类型断言将允许您的代码编译,即使数组包含无效字符串也是如此。例如,如果您稍后更新 Placement 类型,TypeScript 将不会抱怨此代码,即使它在逻辑上不再正确:

type Placement = "up" | "down" | "left" | "right";

const isHorizontal = (placement: Placement): boolean =>
  (["top", "bottom"] as Placement[]).includes(placement);