简体   繁体   English

限制 Typescript 中 React Component prop 的类型

[英]Restrict the type of React Component prop in Typescript

To achieve composition in our codebase we pass components as props.为了在我们的代码库中实现组合,我们将组件作为道具传递。 Is it possible to type check the component that is passed as a prop?是否可以键入检查作为道具传递的组件? As an example, I make use of a Typography component.例如,我使用了一个Typography组件。 This component is used in the entire codebase and is passed as a prop to many other components.该组件在整个代码库中使用,并作为道具传递给许多其他组件。

interface TypographyProps {
  variant:
      | 'h1'
      | 'small'
}

<Thumbnail
  name={
    <Typography variant="h4">John Doe</Typography>
  }
  secondaryLine={
    <Typography variant="small">Bakerstreet 122</Typography>
  }
/>

I want to restrict the properties name and secondaryLine to only receiving the Typography component as a prop.我想将属性namesecondaryLine限制为仅接收Typography组件作为道具。 It would be even better to restrict the name prop to only receive the Typography component with this specific variant ( h4 ): <Typography variant="h4"> .name属性限制为仅接收具有此特定变体 ( h4 ) 的 Typography 组件会更好: <Typography variant="h4">

Currently I define the type like this: name: ReactElement<typeof Typography>;目前我这样定义类型: name: ReactElement<typeof Typography>; . . It seems that every component can be used as a prop (not only the Typography component).似乎每个组件都可以用作道具(不仅是Typography组件)。

Is it possible to restrict the component being passed as a prop to this specific type?是否可以将作为道具传递的组件限制为这种特定类型?

Since variant is a prop of Typography , you can specify the of Typography.props in the Typography implementation:由于variantTypography的道具,您可以在 Typography 实现中指定Typography.props的:

interface TypographyProps {
    variant: 'h1' | 'small',
    children: string | JSX.element
}

export const Typography = ({ variant, children }: TypographyProps) => (
    <div className={variant}>{ children}</div>
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM