You have multiple options to accomplish this:
import React, { FC } from 'react'
type Obj = {
name: string
}
type Props = {
arrayValue: Obj[]
}
const Form: FC<Props> = ({ arrayValue }) => {
console.log("Array of Obj", arrayValue)
const x = arrayValue[0].name // okay
return <div></div>;
//This is a large form component....
};
// OR A GENERIC APPROACH
const Form2 = <T>({ arrayValue }: { arrayValue: T[] }) => {
console.log("Array of Obj", arrayValue)
return <div></div>;
//This is a large form component....
};
type Obj2 = { age: number }
Playground
Please note, the generic approach
has its own limitations. You cannot access properties of specific elements in the array, but you can impose certain restrictions (bounds) on the T
argument.
For instance:
const Form2 = <T extends { age: number }>({ arrayValue }: { arrayValue: T[] }) => {
console.log("Array of Obj", arrayValue)
arrayValue[0].age // okay
return <div></div>;
//This is a large form component....
};
type Obj2 = { age: number }
const result = <Form2<Obj2> arrayValue={[{ age: '42' }]} /> // error, because age should be a number