Home > Mobile >  How to pass interface to child component in react using typescript
How to pass interface to child component in react using typescript

Time:07-16

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

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?

CodePudding user response:

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) => {
  • Related