Reputation: 2978
I have some code like this:
type WrapperProps = { wrapperProp: string };
const Wrapper: React.FC<WrapperProps> = ({ children }) => <div>{children}</div>;
type MyCmpnntProps = { myCmpnntProp: string };
const MyCmpnnt: React.FC<MyCmpnntProps> = (props) => (
<Wrapper {...props}>MyCmpnnt in a Wrapper</Wrapper>
);
it work fine if I make this change this
type MyCmpnntProps = WrapperProps & { myCmpnntProp: string };
I want to know if there is a way to not do the union of types. In my mind, React.FC should do this itself, or am I wrong?
Upvotes: 0
Views: 208
Reputation: 439
TL;DR: You are wrong, type systems simply do not work like this.
When you tell the compiler: I have a method that takes variable of type MyCmpnntProps it expects what you said you will give, no more no less. If you want to pass also the props for the wrapper you need to tell that to the compiler, by making a union, either for MyCmpnntProps type or in the component definition like so:
type WrapperProps = { wrapperProp: string };
const Wrapper: React.FC<WrapperProps> = ({ children }) => <div>{children}
</div>;
type MyCmpnntProps = { myCmpnntProp: string };
// Merge the types in the component definition
const MyCmpnnt: React.FC<MyCmpnntProps & WrapperProps> = (props) => (
<Wrapper {...props}>MyCmpnnt in a Wrapper</Wrapper>
);
Upvotes: 1