search

Home  >  Q&A  >  body text

Translation: React - TypeScript destructuring assignment of props

<p>I have a function</p> <pre class="brush:php;toolbar:false;">export function getSubjectsForStudent(data: any) : any[]</pre> <p>The "data argument" is what I receive from an external source and defining a strong type is not feasible. "return" is derived from "data", so it is also of type any. <br /><br />A "Main" component passes "return" to a "child" component, like this: </p><p><br /></ p> <pre class="brush:php;toolbar:false;"><MainCategories subjects={getSubjectsForStudent(data)} /></pre> <p>And in the MainCategories component, </p> <pre class="brush:php;toolbar:false;">export default function MainCategories(props: any) { const tmp = props.subjects; ...</pre> <p>Translation: It works, no problem. </p><p>But I want: </p><p>export default function MainCategories( {subjects} ) {</p><p>Can anyone help? </p><p><br /></p>
P粉071602406P粉071602406487 days ago500

reply all(2)I'll reply

  • P粉579008412

    P粉5790084122023-07-28 12:34:25

    You need to add a Props type or interface, and then you can obtain subjects through destructuring.

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

    reply
    0
  • P粉155710425

    P粉1557104252023-07-28 00:35:26

    I often use this pattern to achieve this, but the main key is defining the props.

    import { FunctionComponent } from 'react';
    
    interface Props {
      // In your case
      subjects: any
    }
    
    const MainCategories: FunctionComponent<Props> = ({subjects}) => (
      ...
    );
    
    export default MainCategories;

    reply
    0
  • Cancelreply