'How to setup styled-components' "css prop" in a React Native + Typescript project?

I'm trying to setup my Expo project so that Styled Components' "css prop" correctly works with TypeScript.

So far I:

  • Installed @types/styled-components, styled-components, and babel-plugin-styled-components;
  • Enabled the Babel plugin;
  • Created a types/styled.d.ts file where I defined my own theme as explained by the styled-components documentation;
  • Added a ThemeProvider wrapper around my App component and assigned it my theme;
  • Added /// <reference types="styled-components/cssprop" /> to the top of my App.tsx
    • I also tried with import type {} from 'styled-components/cssprop';
    • I tried also import {} from 'styled-components/cssprop'; but it generated an error: styled-components/cssprop could not be found within the project.

This got me in a good place where I can use the css property on any React component and it gets properly applied as style.

The last remaining problem I'm having is that when I try to use my theme, as follows, I get a Parameter 'props' implicitly has an 'any' type.ts(7006) error:

<View
  css={`
    background-color: yellow;
    margin: ${(props) => props.theme.spacing.small}px;
  `}
>
  <Text>Hello, World!</Text>
</View>

I'm not sure how to proceed from here, I would expect the props argument to be populated with my Styled Components' theme.

For completeness, this is my types/styled.d.ts:

// import original module declarations
import 'styled-components';

// and extend them!
declare module 'styled-components' {
  export interface DefaultTheme {
    spacing: {
      small: 8;
      medium: 16;
      large: 24;
    };
  }
}

My project is just the default expo-cli typescript template.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source