打字稿共享属性类型

时间:2020-07-13 11:55:32

标签: typescript

在打字稿中,我有这个界面。

export interface FlexProps {
  justifyContent:
  | "initial"
  | "center"
  | "flex-start"
  | "flex-end"
  | "space-between"
  | "space-around";

  alignItems:
  | "initial"
  | "center"
  | "stretch"
  | "flex-start"
  | "flex-end"
  | "baseline";
}

有没有办法将其转换为?

    const shared: "initial" | "center" | "flex-start" | "flex-end"

    export interface FlexProps {
      justifyContent: shared | "space-between" | "space-around";
      alignItems: shared | "stretch" | "baseline";
    }

1 个答案:

答案 0 :(得分:2)

在声明共享类型时,您可能输入了错误。您已使用const,但应为type

-  const shared: "initial" | "center" | "flex-start" | "flex-end"
+  type shared = "initial" | "center" | "flex-start" | "flex-end";

   export interface FlexProps {
     justifyContent: shared | "space-between" | "space-around";
     alignItems: shared | "stretch" | "baseline";
   }

这里是demo

type shared = "initial" | "center" | "flex-start" | "flex-end";

interface FlexProps {
    justifyContent: shared | "space-between" | "space-around";
    alignItems: shared | "stretch" | "baseline";
}