Velvet Star Monitor

Standout celebrity highlights with iconic style.

news

React.memo with typescript in react

Writer Sebastian Wright

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???

3

1 Answer

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.

type MyComponentProps { children: React.ReactNode;
}

Read more

2

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.