“字符串类型的参数不能分配给自定义类型的参数”的难看的问题

时间:2019-12-10 10:44:06

标签: javascript reactjs typescript react-tsx

我有一个有效的打字稿代码,请参见代码段。 TS的问题是,它在消息中指出代码错误:

  

“字符串”类型的参数无法分配给类型的参数   'SetStateAction <“垂直” | “水平” | “垂直反转” |   “ horizo​​ntal-reverse”>'。

如何编写此代码清理器?我考虑过使用类型或枚举,但是随后我进行了许多不必要的强制转换,从而降低了可读性,并且由于我为此编写了很多代码,因此变成了意大利面条式代码。

代码在这里:

const directionItems = [
    { key: 0, label: "vertical" },
    { key: 1, label: "horizontal" },
    { key: 2, label: "vertical-reverse" },
    { key: 3, label: "horizontal-reverse" }
  ];

  const [curDirection, setCurDirection] = React.useState<
    "vertical" | "horizontal" | "vertical-reverse" | "horizontal-reverse"
  >("vertical");

<DropDown
   items={directionItems}
   defaultSelectedIndex={3}
   onSelectionChange={value =>
   setCurDirection(directionItems[value].label) // <-- this is where the compiler gets angry even if it just works
 }></DropDown>

这里也是使用枚举的方法,但是我认为使用这种方法可以编写大量代码,或者这是合法的吗? (使用这种方法,编译器不会出错):

enum position {
    "top",
    "bottom",
    "left",
    "right",
    "in-between"
  }

  const buttonPositionItems = [
    { key: 0, label: position[0] },
    { key: 1, label: position[1] },
    { key: 2, label: position[2] },
    { key: 3, label: position[3] },
    { key: 4, label: position[4] }
  ];

  const [curButtonPosition, setButtonPosition] = React.useState<position>(
    position.right
  );

 <DropDown
    items={buttonPositionItems}
    defaultSelectedIndex={3}
    onSelectionChange={value =>
      setButtonPosition(
      (buttonPositionItems[value].label as unknown) as position)
    }
></DropDown>

我的解决方案现在(我没有使用该界面..)

export type DirectionType = | "vertical" | "horizontal" | "vertical-reverse" | "horizontal-reverse";

const directionItems = [
    { key: 0, label: "vertical" },
    { key: 1, label: "horizontal" },
    { key: 2, label: "vertical-reverse" },
    { key: 3, label: "horizontal-reverse" }
  ];

  const [curDirection, setCurDirection] = React.useState<DirectionType>(
    "vertical"
  );

<DropDown
  onSelectionChange={value =>
     setCurDirection(directionItems[value].label as DirectionType )
     }>/<DropDown>

1 个答案:

答案 0 :(得分:0)

您可能要使用接口来提供显式类型,以便TypeScript识别label的类型为"vertical" | "horizontal" | "vertical-reverse" | "horizontal-reverse"。例如,您可以使用type aliases

export type LabelType = ("vertical" | "horizontal" | "vertical-reverse" | "horizontal-reverse");

export interface DirectionItem {
  key: number;
  label: LabelType;
}

现在,我们可以将接口与您的React Functional Component一起使用。

const directionItems: DirectionItem[] = [
    { key: 0, label: "vertical" },
    { key: 1, label: "horizontal" },
    { key: 2, label: "vertical-reverse" },
    { key: 3, label: "horizontal-reverse" }
  ];

const [curDirection, setCurDirection] = React.useState<LabelType>("vertical");