Interface Infer Prop do componente estilizado
Tento inferir a Propsinterface dos meus componentes ao exportá-los sempre que possível. Este não é um problema com a classe e os componentes funcionais, mas se eu tentar inferir a Propsinterface de a styled-component, o prop é digitado, o anyque não é o ideal.
interface Props {
bgColor: string;
children: React.ReactNode;
}
const Box = styled.div<Props>`
background-color: ${(p) => p.bgColor};
`;
const Button = (props: Props) => (
<button style={{ backgroundColor: props.bgColor }}>{props.children}</button>
);
type ButtonInferredProps = React.ComponentProps<typeof Button>;
type BoxInferredProps = React.ComponentProps<typeof Box>;
const OtherBox = (props: BoxInferredProps) => (
<div style={{ backgroundColor: props.bgColor }}>{props.children}</div>
);
const OtherButton = (props: ButtonInferredProps) => (
<button style={{ backgroundColor: props.bgColor }}>{props.children}</button>
);
export default function App() {
return (
<>
<Box bgColor="red">Hi! I'm a box! </Box>
<OtherBox bgColor="purple" backgroundColor="red">
Hi! I'm another box
</OtherBox>
<Button bgColor="blue">Hi! I'm a button</Button>
<OtherButton bgColor="green">Hi! I'm another button</OtherButton>
</>
);
}
Com Boxsendo um styled-component, eu não posso inferir corretamente sua interface Props. Quando eu crio outro componente que usa tentativas de usar o tipo de Props inferido, ele surge como qualquer:
const OtherBox = (props: BoxInferredProps) => (
{/* TS won't complain that `props` doesn't have a `iAmNotTyped` property which is desired... */}
<div style={{ backgroundColor: props.iAmNotTyped}}>{props.children}</div>
);
https://codesandbox.io/s/styled-components-typescript-forked-7cq4q?file=/src/App.tsx
Respostas
Você pode definir um tipo como este:
import {
StyledComponentInnerComponent,
StyledComponentInnerOtherProps,
AnyStyledComponent
} from 'styled-components';
type inferStyledTypes<T extends AnyStyledComponent> =
React.ComponentProps<StyledComponentInnerComponent<T>>
& StyledComponentInnerOtherProps<T>;
// Use the above type to infer the props:
type BoxInferredProps = inferStyledTypes<typeof Box>
O tipo do seu componente estilizado Box está sendo exibido como StyledComponent<"div", any, Props, never>. Portanto, você pode usar a inferpalavra-chave typescript para extrair Props dessa definição de tipo.
import {StyledComponent} from "styled-components";
type StyledComponentProps<T> = T extends StyledComponent<any, any, infer P, any> ? P : never
type BoxInferredProps = StyledComponentProps<typeof Box>;
Agora você obtém um erro de backgroundColordigitação , como esperado, ao tentar atribuir em OtherBox.
styled-components exporta um auxiliar do Typescript para isso.
Chama-se StyledComponentPropsWithRef:
import React from 'react';
import styled, { StyledComponentPropsWithRef } from 'styled-components';
const RedLink = styled.a`
color: red;
`;
type Props = StyledComponentPropsWithRef<typeof RedLink>;
const Link = (props: Props) => <RedLink {...props} />;
export default function App() {
return <Link href="/" role="button" />;
}
Este código funciona ☝️