Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Passing string literal as a single prop in Typescript + React

It seems this concept is so basic, there’s a lack of documentation about it. I can pass objects as props, but can’t seem to pass a basic string literal.

Functional Component

I have a functional component that takes a typed prop, like so:

const ChildComponent = (name: string) => {
    return (
        <div className={styles.childComponent}>
            <p className={styles.styledName}>
                { name }
            </p>
        </div>
    );
}

and call it like so:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<ChildComponent name="testName" />

Error

VSCode throws the error on ChildComponent:

Type ‘{ name: string; }’ is not assignable to type ‘string’

I’m very new to Typescript, but from what I can tell, it’s reading the string literal as an object.

Possible Solutions

Much of what I’ve read advises creating a custom typed prop, even for a single property, like so:

Type: NameProp {
name: string
}

and using that as the prop type, instead of string.

Isn’t this overkill? Or am I missing something very basic.

>Solution :

const ChildComponent = ({ name }: { name: string }) => {
    return (
        <div className={styles.childComponent}>
            <p className={styles.styledName}>{name}</p>
        </div>
    );
};
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading