【问题标题】:Generic Props for Typescript type checkTypescript 类型检查的通用道具
【发布时间】:2018-08-20 07:30:50
【问题描述】:

我想写一个组件来接收组件和道具,并通过注入自定义道具进行渲染

type InjectProps<P> = {
  custom: string
} & P

interface Props<P> {
  component: React.ComponentType<InjectProps<P>>
  componentProps: P
}

class PropInjector<T> extends Component<Props<T>> {
  ...
  render() {
    const GivenComponent = this.props.component
    return (
      // in my case, Wrapper is needed for some reason.
      <Wrapper>
        <GivenComponent {...this.props.componentProps} custom="props" />
      <Wrapper />
    )
  }
}

当我用Input 测试时,哪些道具是这样定义的,

interface InputProps {
  custom: string
  value: string
  onChange(value: string): void
}
class Input extends Component<InputProps> { ... }

我认为 typescript 可以在下面的代码上推断和类型检查,但它没有抛出任何错误。

render() {
  return (
    // should throw error about not existing Input's required props like value, onChange ....
    // But no error
    <PropInjector component={Input} componentProps={{}} />
  )
}

如何让 Typescript 推断出P,并在使用PropInjector 时使用P 对componentProps 进行一些类型检查?

【问题讨论】:

    标签: reactjs typescript generics


    【解决方案1】:

    据我所知,目前 TypeScript 无法做到这一点。在您的最终render() 方法中,您没有为PropInjector 提供通用值。因此 TypeScript 不知道 T 应该在 PropInjector 中是什么。

    一种解决方法是像这样定义一个中间组件:

    class InputPropInjector extends PropInjector<InputProps> { }
    
    class Input extends Component<InputProps> {
        render(): JSX.Element {
            return (
                <InputPropInjector component={Input} componentProps={{}} />
            );
        }
    }
    

    discussion about this 已经有了很多,所以希望将来会有更好的解决方案。

    【讨论】:

    • 谢谢!如果泛型不适用于 JSX,那么我必须放弃键入这些组件。但是您提到的那个问题已经设置为 TS2.9 的里程碑!我将等待并等待该版本的发布:D
    猜你喜欢
    • 2019-01-29
    • 2018-12-10
    • 1970-01-01
    • 2021-02-01
    • 2017-07-31
    • 2021-06-29
    • 2021-02-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多