Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

styled-system props typing with TypeScript

I'm using styled-system and one key of the library is to use the shorthand props to allow easy and fast theming.

I've simplified my component but here is the interesting part:

import React from 'react'
import styled from 'styled-components'
import { color, ColorProps } from 'styled-system'

const StyledDiv = styled('div')<ColorProps>`
  ${color}
`

const Text = ({ color }: ColorProps) => {
  return <StyledDiv color={color} />
}

I have an error on the color prop which says:

Type 'string | (string | null)[] | undefined' is not assignable to type 'string | (string & (string | null)[]) | undefined'.

I think that's because styled-system use the same naming as the native HTML attribute color and it conflicts.

How do I solve this?

like image 747
Kerumen Avatar asked Dec 10 '18 18:12

Kerumen


Video Answer


1 Answers

color seems to be declared in react's declaration file under HTMLAttributes - it's not exported.

I had to work around this by creating a custom prop

Example is using @emotion/styled but also works with styled-components

// component.js
import styled from '@emotion/styled';
import { style, ResponsiveValue } from 'styled-system';
import CSS from 'csstype';

const textColor = style({
  prop: 'textColor',
  cssProperty: 'color',
  key: 'colors'
});


type Props = {
  textColor?: ResponsiveValue<CSS.ColorProperty>
}

const Box = styled.div<Props>`
  ${textColor};
`

export default Box;
// some-implementation.js
import Box from '.';

const Page = () => (
  <Box textColor={['red', 'green']}>Content in a box</Box>
);
like image 107
Chris Avatar answered Sep 27 '22 22:09

Chris