Skip to content

as prop of styled components in TypeScript #1137

@felixjung

Description

@felixjung
  • emotion version: 10.0.5
  • react version: 16.6.3

Relevant code:

// Custom styled function that is typed with my theme interface
import styled, { CreateStyled } from '@emotion/styled'

import { ITheme } from '../theme'

export default styled as CreateStyled<ITheme>

// Style function interface in a Util module
declare module 'Util' {
  import { css } from '@emotion/core'
  import { ITheme } from '../util/theme'

  type CssType = typeof css

  export interface IStyleFunction<P = {}> {
    ( arg0: { theme: ITheme } & P): ReturnType<CssType> | false | null
  }
}

// Component code
type HeadingProps = {
  size?: FontSizes
}

const baseStyles: IStyleFunction<HeadingProps> = ({ theme }) => css`
  font-family: ${theme.fonts.heading};
`

const sizeStyles: IStyleFunction<HeadingProps> = ({
  theme,
  size = 'regular',
}) => {
  const [defaultSize, smallBreakPoint] = fontSizes[size]

  return css`
    font-size: ${theme.fontSizes[defaultSize]};

    ${theme.mq[0]} {
      font-size: ${theme.fontSizes[smallBreakPoint]};
    }
  `
}

const Heading = styled.h3<HeadingProps>(baseStyles, sizeStyles)

// Using the component
<Heading as="h5" size="tiny">
  This is an important heading
</Heading>

What you did:

  • Set up a Next js project with Typescript in strict mode
  • Use Emotion 10
  • Using a customized styled function
  • Using the ThemeProvider
  • Create a styled component and pass the component props as ExtraProps to the styled function
  • When using the styled component pass the as prop from Emotion 10 to change the element being used.

What happened:

Typescript complains about the as prop not existing on the styled component

screenshot 2018-12-28 at 10 56 05

Reproduction:

I've created a code sandbox for this, but I don't think the setup there properly reflects mine. Since you can't seem to customize the tsconfig in the default Typescript + React starter, I don't know what else to do. In any case code sandbox does not show any typescript errors.

https://codesandbox.io/s/mzyzm524lj

Problem description:

I would like to not get compiler warnings about the as prop. If I add as to my component's ExtraProps (in the above example the HeadingProps), the compiler stops complaining.

Thanks a lot for the help. I love emotion and I've been using it for about a year now. Just new to the whole TypeScript thing. 😅

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions