简体   繁体   中英

Typescript - IntrinsicAttributes and children type issues when typing React components

I am migrating my React files to .tsx and have come across this issue.

Footer.tsx

const Footer = ({ children, inModal }) => (
    <footer className={'(inModal ? " in-modal" : "") }>
        <div>
            {children}
        </div>
    </footer>
);

export default Footer;

ParentComponent.tsx

import Footer from 'path/to/Footer';

export class ParentComponent extends React.Component<{ showSomething: (() => void) }> {
    render() {
        return (
            <Footer>
                <Button onClick={() => this.props.showSomething()}>Add</Button>
            </Footer>
        );
    }
}

There is a red underline underneath the <Footer> tag with the error:

[ts] Type '{ children: Element; }' is not assignable to type 'IntrinsicAttributes & { children: any; inModal: any; }'. Type '{ children: Element; }' is not assignable to type '{ children: any; inModal: any; }'. Property 'inModal' is missing in type '{ children: Element; }'.

I'm not quite sure how to decipher what that means. Any help would be greatly appreciated.

The error is indicating that the Footer component requires a prop inModal to be passed to it. To fix the issue, you can either:

Give it a default value:

const Footer = ({ children, inModal = false }) => ...

Tell typescript that it's optional:

const Footer = ({ children, inModal }: {children: any, inModal?: boolean}) => ...

Or explicitly provide that prop whenever you use the footer:

<Footer inModal={false}> ... </Footer>

I see your code and find you have not specify the type of inModal props, I believe it's a good prectice to define interface like that:

export class ParentComponent extends React.Component<{ showSomething: (() => void) }> {

you can modify this something like this:

interface FooterPropsType{
showSomething?:()=> void,
isModal?: boolean,
}

export class ParentComponent extends React.Component<FooterPropsType> {

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