简体   繁体   中英

React - TypeScript destructuring of props

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?

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;

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM