TypeScript & styled-components props type error All In One
TypeScript & styled-components props type error All In One
envinfo
https://www.npmjs.com/package/envinfo
$ npx envinfo --system --binaries --npmPackages styled-components,babel-plugin-styled-components --markdown --clipboard
## System:
- OS: macOS 13.0.1
- CPU: (12) x64 Intel(R) Core(TM) i7-8700B CPU @ 3.20GHz
- Memory: 37.14 MB / 16.00 GB
- Shell: 5.8.1 - /bin/zsh
## Binaries:
- Node: 18.12.0 - ~/.nvm/versions/node/v18.12.0/bin/node
- Yarn: 1.22.19 - /usr/local/bin/yarn
- npm: 8.19.2 - ~/.nvm/versions/node/v18.12.0/bin/npm
## npmPackages:
- styled-components: ^5.3.6 => 5.3.6
styled-components & typescript bug
import React from 'react';
import styled from 'styled-components'
type StyledButtonProp = {
primary?: any;
text?: string;
children: string;
[key: string]: any;
}
// ❌ any Property 'primary' does not exist on type 'ThemedStyledProps<Pick<DetailedHTMLProps<ButtonHTMLAttributes<HTMLButtonElement>, HTMLButtonElement>, "key" | keyof ButtonHTMLAttributes<...>> & { ...; }, any>'.ts(2339)
const Button = styled.button`
background: ${props => props?.primary ? "palevioletred" : "white"};
color: ${props => props?.primary ? "white" : "palevioletred"};
font-size: 1em;
margin: 1em;
padding: 0.25em 1em;
border: 2px solid palevioletred;
border-radius: 3px;
`;
function StyledButton(props: StyledButtonProp) {
return (
<div>
<Button primary {...props}></Button>
</div>
);
}
export default StyledButton;
https://github.com/styled-components/styled-components/issues/new
https://styled-components.com/docs/basics#adapting-based-on-props
https://github.com/styled-components/styled-components/issues/1589
solution
import React from 'react';
import styled from 'styled-components'
type StyledButtonProp = {
[key: string]: any;
}
// const Button = styled.button` ❌
// const Button = styled.button<props: StyledButtonProp>` ❌
// const Button = styled.button<StyledButtonProp>` ✅
const Button = styled.button<StyledButtonProp>`
background: ${props => props?.primary ? "palevioletred" : "white"};
color: ${props => props?.primary ? "white" : "palevioletred"};
font-size: 1em;
margin: 1em;
padding: 0.25em 1em;
border: 2px solid palevioletred;
border-radius: 3px;
`;
function StyledButtonBug(props: StyledButtonProp) {
return (
<div>
<Button primary {...props}></Button>
</div>
);
}
export default StyledButtonBug;
(🐞 反爬虫测试!打击盗版⚠️)如果你看到这个信息, 说明这是一篇剽窃的文章,请访问 https://www.cnblogs.com/xgqfrms/ 查看原创文章!
refs
https://github.com/styled-components/styled-components/issues/3894
©xgqfrms 2012-2021
www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!
原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!
本文首发于博客园,作者:xgqfrms,原文链接:https://www.cnblogs.com/xgqfrms/p/16987357.html
未经授权禁止转载,违者必究!