The object properties in the array are interdependent eg when call AComponent
I want componentProps must be Type1Props, when items.type === 'type1',
if items.type === 'type2' componentProps shoud be Type2Props
//I want componentProps must be Type1Props, when ` items.type === 'type1' `, if `items.type === 'type2'` componentProps shoud be Type2Props
<AComponent items= {[
{type:'type1', componentProps{ }}
{type:'type2', componentProps{ }
]}>
Below is AComponent.tsx code
// if type === type1 the value must be constraint with Type1Props
type ComTypes = {
type1 : Type1Props,
type2 : Type1Props,
type2 : Type1Props,
}
type ItemType =
'type1'
| 'type2'
| 'type3'
// The object properties in the array
type ItemProps<T> = {
type: T
componentProps: ComTypes[T]
showItem?: boolean
}
interface Props extends FormProps {
itemsArray: QDItemProps[]
}
const AComponent: FC<Props> = ({itemsArray}) => {
}
export default AComponent
I do not know how to solove this scene
You can use union types to do this. I'll give you a more generic example that is not using react, for the benefit of others who may stumble upon this question.
type Type1Props = "A";
type Type2Props = "B";
type Type3Props = "C";
type PropTypes =
| {
type: "type1",
componentProps: Type1Props,
}
| {
type: "type2",
componentProps: Type2Props,
}
| {
type: "type3",
componentProps: Type3Props,
};
const p1: PropTypes = {
type: "type1",
componentProps: "A",
};
const p2: PropTypes = {
type: "type2",
componentProps: "B",
};
You should be able to extend this for your use case.