I have encountered this unassignable error regarding the relaying props from one component to another component:
type ChildProps = { value: number } | { value: Array<number> };
const Child = ({ value }: ChildProps) => {
return <div>{`${value}`}</div>;
};
const Parent = ({ value }: ChildProps) => {
return <Child value={value} />; // TypeScript complains about this error here: `Type 'number' is not assignable to type 'number[]'.(2322)` (see below for the full error message)
};
const App = () => {
return (
<div>
<Parent value={10} />
</div>
);
};
You can also see this in StackBlitz here.
And here is the full error message I got:
Type '{ value: number | number[]; }' is not assignable to type 'IntrinsicAttributes & ChildProps'.
Type '{ value: number | number[]; }' is not assignable to type '{ value: number[]; }'.
Types of property 'value' are incompatible.
Type 'number | number[]' is not assignable to type 'number[]'.
Type 'number' is not assignable to type 'number[]'.(2322)
Is there any way to properly type the <Parent/>
component in the following code snippet, so that we can fix the TypeScript error?
Unfortunately, the <Child/>
component and thus the ChildProps
are not owned by me and I cannot change them.