I'm trying to strict type a Button component in React.
How can I expect a prop with a specific string value?
My current attempt results in Type '"primary"' is not assignable to type 'ButtonLevel'
enum ButtonLevel {
Primary = "primary",
Secondary = "secondary",
Warning = "warning"
}
interface IButtonProps {
level: ButtonLevel,
disabled?: boolean
}
function MyButton(props: IButtonProps) {
return (<Button>ABC</Button>)
}
function test() {
return (<MyButton level="primary" ></MyButton>)
}
Right... just enter the values pipe separated
interface IButtonProps {
level: "primary" | "secondary" | "warning",
disabled?: boolean
}
function test() {
return (<MyButton level="ad" disabled >Continue</MyButton>)
}
Which then warns a component consumer the value is invalid.
当您使用枚举时,您传递的是 ButtonLevel.Primary 而不是“primary”,枚举的重点是强类型并防止输入错误。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.