Generi c компонент React высшего порядка дает ошибки типа - PullRequest
1 голос
/ 25 января 2020

Я пытаюсь написать обобщенный c компонент React, который требует реквизиты одного из двух типов (IFoo или IBar) и компонент, который принимает реквизиты выбранного типа.

Почему следующее не работает?

Детская площадка

import React from 'react';

interface IFoo {
  x: string;
}

interface IBar {
  x: number;
}

const foo: React.FunctionComponent<IFoo> = (props: IFoo) => {
  console.log("hello from foo!");
  return <div>foo</div>
};

const bar: React.FunctionComponent<IBar> = (props: IBar) => {
  console.log("hello from bar!");
  return <div>bar</div>
};

interface IProps<T> { 
    props: T[];
    Component: React.FunctionComponent<T>;
}


class HigherOrderComponent<T extends IBar | IFoo> extends React.Component<IProps<T>> { 
    render() {
        const { props, Component } = this.props;
        return (<div>
            {props.map(prop => <Component {...prop}/>)};
        </div>)
     }
}

Это возвращает следующую ошибку:

Type 'T' is not assignable to type 'IntrinsicAttributes & T & { children?: ReactNode; }'.
  Type 'IFoo | IBar' is not assignable to type 'IntrinsicAttributes & T & { children?: ReactNode; }'.
    Type 'IFoo' is not assignable to type 'IntrinsicAttributes & T & { children?: ReactNode; }'.
      Type 'IFoo' is not assignable to type 'T'.
        'IFoo' is assignable to the constraint of type 'T', but 'T' could be instantiated with a different subtype of constraint 'IFoo | IBar'.
          Type 'T' is not assignable to type 'IntrinsicAttributes'.
            Type 'IFoo | IBar' is not assignable to type 'IntrinsicAttributes'.
              Type 'IFoo' has no properties in common with type 'IntrinsicAttributes'.(2322)

Ответы [ 2 ]

1 голос
/ 26 января 2020

Быстрое исправление заключается в добавлении:

{props.map((prop: T & {}) => <Component {...prop}/>)};

Я думаю, что проблема с оператором распространения и типом объединения (если есть только один тип, он работает нормально). Я знаю, что у TS были проблемы с этим раньше: (

Надеюсь, это поможет:)

1 голос
/ 25 января 2020

Вам необходимо создать класс HO C динамически, чтобы обернуть Компонент и правильно набрать для него

import React from 'react';

interface IFoo {
  x: string;
}

interface IBar {
  x: number;
}

const foo: React.FunctionComponent<IFoo> = (props: IFoo) => {
    console.log("hello from foo!");
  return <div>foo</div>
};

const bar: React.FunctionComponent<IBar> = (props: IBar) => {
    console.log("hello from bar!");
  return <div>bar</div>
};

function createHOC<P extends IFoo | IBar>(Component: React.ComponentType<P>) {
  return class HigherOrderComponent extends React.Component<P> {
    render() {
        console.log(this.props.x)
        return <Component {...this.props} />
     }
  }
}

const WrapperFooComponent = createHOC(foo)

const WrapperBarComponent = createHOC(bar)

Надеюсь, это поможет <3 </p>

...