从样式组件推断 Prop 接口

Mis*_*pic 9 typescript reactjs styled-components

Props我尝试尽可能推断组件的接口而不是导出它们。这不是类和功能组件的问题,但如果我尝试推断Propsa 的接口styled-component,则输入的 propany并不理想。

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>
    </>
  );
}
Run Code Online (Sandbox Code Playgroud)

作为Boxstyled-component我无法正确推断其 Props 接口。当我创建另一个尝试使用推断的 Props 类型的组件时,它会出现如下情况:

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>
);
Run Code Online (Sandbox Code Playgroud)

https://codesandbox.io/s/styled-components-typescript-forked-7cq4q?file=/src/App.tsx

Ram*_*zar 6

styled-components为此导出一个 Typescript 助手。

\n

它的名字叫StyledComponentPropsWithRef

\n
import React from 'react';\nimport styled, { StyledComponentPropsWithRef } from 'styled-components';\n\nconst RedLink = styled.a`\n  color: red;\n`;\n\ntype Props = StyledComponentPropsWithRef<typeof RedLink>;\n\nconst Link = (props: Props) => <RedLink {...props} />;\n\nexport default function App() {\n  return <Link href="/" role="button" />;\n}\n
Run Code Online (Sandbox Code Playgroud)\n

此代码有效 \xe2\x98\x9d\xef\xb8\x8f

\n


Has*_*qvi 2

您可以定义这样的类型:

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>
Run Code Online (Sandbox Code Playgroud)