Alec Mather
Alec Mather

Reputation: 838

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

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?

Upvotes: 0

Views: 1038

Answers (1)

Nicholas Tower
Nicholas Tower

Reputation: 84982

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

Upvotes: 2

Related Questions