为什么我的枚举类型在 Next.js 项目中不起作用

Why my enum type wont work in Next.js project

我收到这个错误 “类型 'string' 不可分配给类型‘‘left’ | ‘right’’。”

项目 运行 Next.js

这是我的类型定义

export interface TwoColumnsBlueWhite {
  title: String;
  subTitle: String;
  content: JSX.Element;
  links: string[];
  imageSide: 'left' | 'right'
}

这是我的地图数组。

const data = [
{ title: 'some'
  ...
  imageSide: 'left'
 },
{ title: 'some'
  ...
  imageSide: 'right'
 },
];

<Carousel />
      {data.map((data) => (
        <TwoColumnsBlueWhite
          title={data.title}
          subTitle={data.subTitle}
          content={data.content}
          links={data.links}
          imageSide={data.imageSide}
        />
      ))}

我试试

将手动放入 props 'left' 或 'right' 中,然后工作,但我需要这个组件图。

如果我改变我的定义 图片面:'left' | 'right' |字符串

然后工作,但我想使用严格类型..

'left''right' 不是 imageSide: 'left' | 'right' 中的 typeenum type

一个解决方案可能是您首先定义枚举类型,如下所示,

export enum ISide {
   LEFT = 'left',
   RIGHT = 'right'
}

然后,在需要的时候使用它,

export interface TwoColumnsBlueWhite {
  title: String;
  subTitle: String;
  content: JSX.Element;
  links: string[];
  imageSide: ISide.LEFT | ISide.RIGHT           // <--- import ISide and use it here as shown
}

另外,

const data = [
{ title: 'some'
  ...
  imageSide: ISide.LEFT                         // <---- check this
 },
{ title: 'some'
  ...
  imageSide: ISide.RIGHT                        // <---- check this
 },
];

我做了与其他答案类似的事情,但将其转换为 const。它可以防止扩大和必须设置您明确允许的选项。

const OPTIONS = {
   LEFT = 'left',
   RIGHT = 'right'
} as const;

type TImageSlide = typeof OPTIONS[keyof typeof OPTIONS];

export interface TwoColumnsBlueWhite {
  imageSide: TImageSlide,
  ...other options
}