Как получить поток данных для проверки типа данных, предоставленных ему из HOC?

Например:

import { withProps } from 'recompose'

type Props = {
  name: string,
};

const NameTag = ({ name }: Props) => (
  <p style={{color: 'pink'}}>
    { name }
  </p>
);

const MyNameTag = withProps({
  // i want a error here
  name: 1
})(NameTag);

Как я могу получить сообщение об ошибке, что я не могу передать номер 1 к опоре name для компонента NameTag?

Благодарю.

1 ответ

По крайней мере, поток 0.78 выдаст вам ошибку, как только вы используете HOC.

Так что, если вы добавите <MyNameTag /> в вашем коде, это должно дать вам это.

string [1] is incompatible with number [2] in property name of the first argument.

 [1]  7│   name: string,
      8│ };
      9│
     10│ const NameTag = ({ name }: Props) => (
     11│   <p style={{color: 'pink'}}>
     12│     { name }
     13│   </p>
       :
 [2] 19│   name: 1

Это, вероятно, происходит потому, что вы все еще можете пройти name при создании экземпляра NameTag и до этого момента не ясно, что он потерпит неудачу.

Поток настолько сложен, а мой поток слаб, поэтому я не осмелюсь сказать, что это ошибка потока.

До сих пор я обнаружил, что единственный способ отловить ошибки в объявлениях - это создать HOC, который допускает только те свойства, которые не были переопределены, и ничего более. Вам нужно будет объявить компоненты со строгими свойствами {| a: string |}, Проверьте этот пример:

// @flow

import * as React from 'react'


function myWithProps<
    MP, // My Properties. These are the pre-entered properties.
    CP, // Component properties. The properties originally expected by
        // the component.
    C: React.ComponentType<CP>, // The original component itself. Used to
                                // extract the properties template CP.
    IP: $Diff<CP, MP>, // Input properties. Properties that must be received
                       // by the HOC. We only expect the properties of the
                       // original component CP minus the properties MP that
                       // were specified when we created the HOC.
    >(myProps: MP): C => React.ComponentType<IP> {
        return component => props => <component {...myProps} {...props} />;
}


type Props = {|
  name: string,
  age: number,
|};


const NameTag = ({ name, age }: Props) => (
  <p style={{color: 'pink'}}>
    { name } { age }
  </p>
);


// $ExpectError. name has a wrong type.
const MyNameTag = myWithProps({name: 1})(NameTag);

// Should work.
const MyOtherNameTag = myWithProps({name: "hello"})(NameTag);

// Should work.
<MyOtherNameTag age={21} />;

// $ExpectError. name cannot be overriden.
<MyOtherNameTag age={21} name={"John"} />;

// $ExpectError. age has a wrong type.
<MyOtherNameTag age={"21"} />;

// $ExpectError. age missing.
<MyOtherNameTag />;

// $ExpectError. Unexpected parameter.
<MyOtherNameTag age={21} nmae={"John"} />;

myWithProps использует универсальные типы, поэтому он должен работать с любым классом.

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

Другие вопросы по тегам