React.F C<SpecificProps> не назначается для React.F C<GenericProps>, но реквизиты назначаются - PullRequest
1 голос
/ 19 апреля 2020

У меня есть реквизиты для компонента:

interface SpecyficProps {
  data: {
    body: string
  }
}

, которые можно назначить на абстрактные реквизиты

interface ComponentProps {
  data: {
    [propName: string]:
      | string
      | number
      | ComponentProps
      | ComponentProps[]
      | undefined
  }
}

const specyficProps: SpecyficProps = {
  data: {
    body: 'xxxx',
  },
}

// ok
const universalProps: ComponentProps = specyficProps

, но FunctionalComponents с использованием этого реквизита не являются:

const specyficComponent: React.FC<SpecyficProps> = ({ data }) => null

// error
const universalComponent: React.FC<ComponentProps> = specyficComponent
Type 'FC<SpecyficProps>' is not assignable to type 'FC<ComponentProps>'.
  Types of parameters 'props' and 'props' are incompatible.
    Type 'PropsWithChildren<ComponentProps>' is not assignable to type 'PropsWithChildren<SpecyficProps>'.
      Type 'PropsWithChildren<ComponentProps>' is not assignable to type 'SpecyficProps'.
        Types of property 'data' are incompatible.
          Property 'body' is missing in type '{ [propName: string]: string | number | ComponentProps | ComponentProps[] | undefined; }' but required in type '{ body: string; }'.(2322)
input.tsx(16, 5): 'body' is declared here.

Как определить типы компонентов, которые можно назначить?

игровая площадка

1 Ответ

1 голос
/ 20 апреля 2020

Эта ошибка происходит от strictFunctionTypes, , введенных в 2.6 . Когда это скомпилируется, одно «решение» - отключить это. Одним из альтернативных подходов является введение иерархий в ваших интерфейсах. Пусть самый нижний интерфейс будет подтипом самого верхнего, и он скомпилируется. По сути эти изменения

type HigherMost = SpecyficProps | ComponentProps 

const specyficComponent: React.FC<HigherMost> = ({ data }) => null

// ok
const universalComponent: React.FC<ComponentProps> = specyficComponent
...