简体   繁体   中英

React.memo with typescript in react

I am using React.memo() in a .tsx file(React typescript)

Now I have declared an interface for Props as:

interface Props {
  type?: string;
}

My component looks like:

const Component: React.SFC<Props> = props => {
  /// return something;
};

export default memo(Component);

Now since type is an optional prop I intend to use it only sometimes.

If I use my component as <Component type="something" /> everything is okay. But if I use it as <Component /> I get the error -->

Type '{ children: string; }' has no properties in common with type 'IntrinsicAttributes & Props'.

This seems to be a very absurd error as I have tried this on Code sandbox and everything works fine. Any ideas about what the error could be?

UPDATE

If I explicitly add a prop in interface like

interface Props {
  type?: string;
  children?: ReactNode;
}

then in that case everything works fine. This is supposed to be implicit but acc to the error its taking as

'{ children: string; }'

Any ideas???

I believe there is an error in typings. Changing

function memo<P extends object>(
  Component: SFC<P>,
  propsAreEqual?: (
    prevProps: Readonly<PropsWithChildren<P>>,
    nextProps: Readonly<PropsWithChildren<P>>
  ) => boolean
): NamedExoticComponent<P>;

to

function memo<P extends object>(
  Component: SFC<P>,
  propsAreEqual?: (
    prevProps: Readonly<PropsWithChildren<P>>,
    nextProps: Readonly<PropsWithChildren<P>>
  ) => boolean
): NamedExoticComponent<PropsWithChildren<P>>;

fixes the issue

UPDATE

Well, actually it is not a bug. See discussion .

TLTR: You have to specify children in component props type.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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