Answer a question

As per styled-components v4, .extend is deprecated, the correct way to extend, or compose components is:

const ButtonA = styled('button')`color: ${props => props.color};`
const ButtonB = styled(ButtonA)`background: 'white';`

However I can't find the correct way to do this with TS, as I get some errors, for example:

import styled from "styled-components";

// Let's create ButtonA
type ButtonAProps = { a: string };
const ButtonA = styled<ButtonAProps, "button">("button")`
  color: ${props => props.a};
`;

// So, here is what I've tried

// Fail #1
// =======
type ButtonBProps = { b: string };
const ButtonB = styled<ButtonBProps, ButtonAProps>(ButtonA)`
  background: ${props => props.b};
`; // Here I get autocompletion only for B props :(
const Test = () => <ButtonB a="something" />; // And here I get autocompletion only for A props :(

// Fail #2
// =======
type ButtonBProps = { b: string } & ButtonAProps;
const ButtonB = styled<ButtonBProps, ButtonAProps>(ButtonA)`
  background: ${props => props.b};
`; //  Here I get autocompletion for A & B props, good!
const Test = () => <ButtonB a="something" />; // Here I still get autocompletion only for A props :(

// Fail #3
// =======
type ButtonBProps = { b: string } & ButtonAProps;
const ButtonB = styled<ButtonBProps, ButtonBProps>(ButtonA)` // Property 'b' is missing in type 'ButtonAProps', of course
  background: ${props => props.b};
`; //  Here I get "props has implicitly any type"
const Test = () => <ButtonB />; // Here I don't get any type checking at all

Seems to be almost there, but can't figure it out.

Any advices? Thank you!

Answers

As of September 2019, the following code also works:

// First extend ButtonAProps with an additional prop
interface ButtonBProps extends ButtonAProps {
  b:string;
}

// ButtonB Component
const ButtonB = styled(ButtonA)<ButtonBProps>`
  background: ${props => props.b};
`;
Logo

React社区为您提供最前沿的新闻资讯和知识内容

更多推荐