7

I have a function:

 export function getSubjectsForStudent(data: any) : any[]

"data argument" I receive from external source and it's not feasible to define strong type. "return" is derived from "data" so it's of type any as well.

A "Main" component passes "return" to a "child" component like this:

<MainCategories subjects={getSubjectsForStudent(data)} />

And in MainCategories

export default function MainCategories(props: any) {
    const tmp = props.subjects;
    ...

It works and it's Ok.

But I want
export default function MainCategories( {subjects} ) {

Can anybody help with it?

3 Answers 3

12

You need to add a type/interface of Props - Then you'll be able to get subjects by destructuring.

interface Props {
  subjects: any
}

export default function MainCategories({ subjects }: Props) {
    const tmp = props.subjects;
    ...
Sign up to request clarification or add additional context in comments.

Comments

11

I often use this pattern to do that, but the main point is to define the props.

import { FunctionComponent } from 'react';

interface Props {
  // In your case
  subjects: any
}

const MainCategories: FunctionComponent<Props> = ({subjects}) => (
  ...
);

export default MainCategories;

1 Comment

This looks nice but what if you have several members defined on the Props and then you duplicate the same names in the destructuring object of the function parameters? You'd end up with code duplication...
2

All other answers use an external interface declaration, which is a good practice. But for everyone looking for an one-liner destructuring, here it goes:

function Foo({name}: {name: string}) {
    return <div>{name}</div>;
}

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.