【发布时间】:2021-01-11 05:16:30
【问题描述】:
我尝试推断我的组件的Props 接口而不是尽可能导出它们。这不是类和函数组件的问题,但如果我尝试推断styled-component 的Props 接口,则prop 类型为any,这并不理想。
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>
</>
);
}
Box 是 styled-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>
);
https://codesandbox.io/s/styled-components-typescript-forked-7cq4q?file=/src/App.tsx
【问题讨论】:
标签: reactjs typescript styled-components