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

How to pass interface to child component in react using typescript

Ok I’m new to using Typescript for react, but I’ve been programming long enough that this problem makes me feel very dumb…

Literally all I want to do, is define an interface that acts as the type for a property that you pass to a child component.

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

interface Foo {
    bar: string;
}

const Child = ({ foo } : Foo) => {

    console.log(foo)

    return <Text>Hello World</Text>

}

const TestPage = () => {

    const fooObject : Foo = { bar: 'something' }

    return <Child foo={fooObject} />

}

But I keep seeing this error underlining the foo property I pass in inside the return statement on the TestPage component:

Type '{ foo: Foo; }' is not assignable to type 'IntrinsicAttributes & Foo'.
  Property 'foo' does not exist on type 'IntrinsicAttributes & Foo'.

And this error underlining the deconstructed foo property coming in on the child component:

Property 'foo' does not exist on type 'Foo'.

This seems so basic to me, can someone please explain?

>Solution :

const Child = ({ foo } : Foo) => {

This means that the entire props object is a Foo. It does not mean that foo is a Foo. You want:

const Child = ({ foo }: { foo: Foo }) => {

Or giving it a named type:

interface ChildProps {
  foo: Foo
}

const Child = ({ foo }: ChildProps) => {
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