我有一个带有prop的组件,我想将其限制为只能选择字符串,因此我使用的是union类型,如下所示:
type HeadingProps = {
level?: 'h1' | 'h2' | 'h3' | 'h4'| 'h5' | 'h6'
}
const Heading: React.FC<HeadingProps> = ({children, level = 'h2'}) => {
return <Box as={level} />
}
按原样使用,效果很好。
<Heading level="h1">Hello, world!</Heading>
但是,如果我尝试将其与数组一起使用,则会收到错误消息:
{['h1', 'h2', 'h3', 'h4', 'h5', 'h6'].map((level: string) => (
<Heading level={level}>{level}</Heading>
)}
类型'string'不能分配给类型'“ h1” | “ h2” | “ h3” | “ h4” | “ h5” | “ h6” | undefined'.ts(2322)
我怎样才能知道prop的类型,以便只有这些字符串有效,但是当在上述数组中使用组件时,要传递有效的字符串值?
编辑这是当前类型的方式:
export const HeadingLevels = {
h1: `h1`,
h2: `h2`,
h3: `h3`,
h4: `h4`,
h5: `h5`,
h6: `h6`,
}
export type Level = keyof typeof HeadingLevels
type HeadingProps = BoxProps & {
level?: Level
}
['h1', 'h2', 'h3', 'h4', 'h5', 'h6']
由编译器推断为类型,string[]
因为通常这是正确的做法,例如
const arr = ['h1', 'h2', 'h3', 'h4', 'h5', 'h6']; // inferred as string[]
arr.push("h7"); // okay
但是在您的情况下,您希望编译器知道该数组的内容始终是(并且只要您使用它就一直)是您设置的特定字符串文字。
从TypeScript 3.4开始,处理此问题的最简单方法是使用一个const
断言来告诉编译器您的数组旨在作为您从中读取特定字符串文字的对象:
(['h1', 'h2', 'h3', 'h4', 'h5', 'h6'] as const).map((level) => (
<Heading level={level}>{level}</Heading>
))
这应该可以正常工作。请注意,我从中删除了类型注释level
。您不想扩大level
到string
,因为那样编译器就无法再确定它是否合适。相反,让编译器根据需要推断的类型level
,它将作为您的union进行"h1"|"h2"|...|"h6"
。
好吧,希望能有所帮助;祝好运!
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句