简体   繁体   中英

Props spread in react with typescript

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?

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>
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM