下一页JS如何解决"Type 'string' is not assignable to type '...' "错误



在我的nextjs-app我有一个按钮组件:

interface IButton {
text: string
theme: 'primary' | 'secondary'
size: 'small' | 'medium' | 'large'
onClick?: () => void
}
const Button = ({ theme, text, size, onClick }: IButton) => {
return (
<button
onClick={onClick}
className={cn(styles.btn, {
[styles.primary]: theme === 'primary',
[styles.secondary]: theme === 'secondary',
[styles.medium]: size === 'small',
[styles.small]: size === 'medium',
[styles.large]: size === 'large',
})}
>
{text}
</button>
)
}
export default Button

我这样使用它:

<Button text="Click me" theme="primary" size="large" onClick={clickHandler} />

当我尝试做npm run build时,我得到错误:

Type 'string' is not assignable to type '"primary" | "secondary"'.
有人能帮我一下吗?

你应该这样使用Enum:

enum ITheme {
PRIMARY = 'primary',
SECONDARY = 'secondary'
};
enum ISize {
SMALL = 'small',
MEDIUM = 'medium',
LARGE = 'large'
};
interface IButton {
text: string
theme: ITheme.PRIMARY | ITheme.SECONDARY
size: ISize.SMALL | ISize.MEDIUM | ISize.LARGE
onClick?: () => void
}

然后像这样使用:

<Button text="Click me" theme={ITheme.PRIMARY} size={ISize.LARGE} />

也可以用另一种方式:

export type ITheme = "primary" | "secondary";
export type ISize = "small" | "medium" | "large";
interface IButton {
text: string
theme: ITheme
size: ISize
onClick?: () => void
};
export const Button = ({ theme, text, size, onClick }: IButton) => {
return (
<button
onClick={onClick}
>
{text}
</button>
)
}
<Button text="Click me" theme={"primary" as ITheme} size={"large" as ISize} />

最新更新