尝试在样式化组件中使用道具时出现 TS 错误

TS errors when trying to use props inside styled-component

我正在使用带类型脚本的样式化组件,并且实际阅读了 docs。如果是简单的造型,不使用道具 - 一切顺利:

interface IButtonWithIcon {
  children: string,
  type?: string,
  size?: number,
}

const ButtonWithIcon = styled<IButtonWithIcon, 'button'>('button')`
  color: black;
  border-radius: 5px;
  cursor: pointer;
`;

但是当我尝试时,甚至只是将道具记录到控制台,就像这样:

const ButtonWithIcon = styled<IButtonWithIcon, 'button'>('button')`
  ${console.log}
  color: black;
  border-radius: 5px;
  cursor: pointer;
`;

TS 开始抱怨:

Argument of type '{ (message?: any, ...optionalParams: any[]): void; (message?: any, ...optionalParams: any[]): voi...' is not assignable to parameter of type 'Interpolation'. Type '{ (message?: any, ...optionalParams: any[]): void; (message?: any, ...optionalParams: any[]): voi...' is not assignable to type 'ReadonlyArray | Interpolat...'. Property 'concat' is missing in type '{ (message?: any, ...optionalParams: any[]): void; (message?: any, ...optionalParams: any[]): voi...'.

如果我添加注释,错误消息会更改:

const ButtonWithIcon = styled<IButtonWithIcon, 'button'>('button')`
${(props: IButtonWithIcon): void => console.log(props)}
color: black;
border-radius: 5px;
cursor: pointer;
`;

Argument of type '(props: IButtonWithIcon) => void' is not assignable to parameter of type 'Interpolation>'. Type '(props: IButtonWithIcon) => void' is not assignable to type 'ReadonlyArray | Interpolat...'. Property 'concat' is missing in type '(props: IButtonWithIcon) => void'.

下面的代码有什么问题?

您插入到 CSS 中的函数必须 return 某些东西。尝试:

const ButtonWithIcon = styled<IButtonWithIcon, 'button'>('button')`
  ${(props) => { console.log(props); return ""; }}
  color: black;
  border-radius: 5px;
  cursor: pointer;
`;