`as` prop of styled components in TypeScript
See original GitHub issueemotion
version: 10.0.5react
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
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. 😅
Issue Analytics
- State:
- Created 5 years ago
- Reactions:45
- Comments:18 (12 by maintainers)
Top GitHub Comments
@Andarist what about
as?: React.ElementType;
? Thats how it’s typed in reflexbox typings.See: https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/reflexbox/index.d.ts#L24
The
as
prop should have a type so it can be used. I just don’t think we want to go near the changing prop types based on the type ofas
.as?: React.ElementType;
seems reasonable. Evenas?: React.ElementType | keyof JSX.IntrinsicElements