Translation: React - TypeScript destructuring assignment of props
P粉071602406
2023-07-27 16:35:13
<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>
You need to add a Props type or interface, and then you can obtain subjects through destructuring.
I often use this pattern to achieve this, but the main key is defining the props.