简体   繁体   中英

TS errors when trying to use props inside styled-component

I am using styled-components with type-script, and actually read docs . When it is simple styling, without using props - all goes right:

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

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

But when I try, even to simply log props to console, like this:

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

TS starts complaining:

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...'.

If I add anotation, the error message changes:

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'.

What is wrong in code below?

Functions that you interpolate into the CSS must return something. Try:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM