1

I have a function defined in a parent component and it gets passed to a child component as a prop. Right now I do the type definitions for the function where it is declared and then I have to do the exact same type definition for the props on the child component.

This feels messy. I know that I could write a type def for the function and store it in some other file and then import that type into both the parent and child. If I do that then I either end up with a big file holding all of these type definitions or a bunch of small files holding fewer type definitions and thinking about both of those options feel a little overwhelming.

What’s the best approach here?

Parent

const foo = (str: string): void => {
    console.log(str);
}
// ...
return <Child foo={foo} />

Child

interface ChildProps {
    foo: (str: string) => void;
}
function Child(props: ChildProps) {
    // ...
}

1 Answer 1

2

You can export ChildProps, then in parent use indexed access operator to get the type of the foo prop:

const foo: ChildProps['foo'] = str => {
    console.log(str);
}

Playground


Or even without exporting child props type, you can use ComponentProps utility to get it:

import { ComponentProps } from 'react';

const foo: ComponentProps<typeof Child>['foo'] = str => {
    console.log(str);
}

Playground

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.