'How Typescript Intersection and Omit works with generic types
Code
type Props = {
prop: string;
};
export default function withProps<T extends Props>(
Component: React.ComponentType<T>
) {
function WithProps({ prop, ...rest }: T) {
// Error: Type '{ prop: string; } & Omit<T, "prop">' is not assignable to type 'T'.
const props: T = {
prop,
...rest
};
return <Component {...props} />;
}
return (props: T) => <WithProps prop="someProp" {...props} />;
}
The code is just an intended demo to demonstrate my question
Error
In line 11, Typescript complains that Type '{ prop: string; } & Omit<T, "prop">' is not assignable to type 'T'
, which is weird to me since I think '{ prop: string; } & Omit<T, "prop">'
should be identical to T
when T extends Props
.
My question is why is this seen as an error by TS and how to fix it.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|