- Published on
Fixing TypeScript Styled-Component Error: IntrinsicAttributes Issue
- Authors
- Name
- Ripal & Zalak
Fixing TypeScript Styled-Component Error: IntrinsicAttributes Issue
If you've encountered the TypeScript error:
Type '{ children: string; }' has no properties in common with type 'IntrinsicAttributes'.ts(2559)
while working with styled-components in a React application, don't worry—you're not alone! This issue commonly occurs due to the incorrect handling of styled-components inside functional components. In this blog, we'll explore the cause and the best way to resolve it.
Understanding the Issue
Consider this React component using styled-components
:
import React from 'react'
import { NotificationSuccess, NotificationError } from '../../styles'
interface IProps {
error?: boolean
message: string
}
export const Notification = (props: IProps) => {
const Note = () => (props.error ? NotificationError : NotificationSuccess)
return <Note>{props.message}</Note> // Error happens here
}
The error occurs because Note
is being treated as a function returning a styled-component, which is not the correct way to reference styled-components in TypeScript.
The Correct Solution
Fix: Assign Styled-Component Directly
Instead of defining Note
as a function, assign it directly as a variable:
export const Notification: React.FC<IProps> = ({ error, message }) => {
const Note = error ? NotificationError : NotificationSuccess
return <Note>{message}</Note>
}
children
Prop
Alternative Fix: Explicitly Define In React 18, children
is no longer an implicit prop for functional components. If your component needs children, define them explicitly:
interface IProps {
error?: boolean
message: string
children?: React.ReactNode
}
export const Notification: React.FC<React.PropsWithChildren<IProps>> = ({
error,
message,
children,
}) => {
const Note = error ? NotificationError : NotificationSuccess
return (
<Note>
{message}
{children}
</Note>
)
}
Frequently Asked Questions (FAQ)
1. Why does TypeScript show the 'IntrinsicAttributes' error?
- TypeScript is expecting a valid React component but instead sees a function that doesn’t accept props.
- Assigning
Note
as a direct variable solves the issue.
React.FC<IProps>
?
2. Why use - It provides better TypeScript support and prevents type mismatches.
children
error?
3. What if I'm using React 18 and get a - React 18 removed
children
as a default prop inReact.FC
. UseReact.PropsWithChildren<IProps>
instead.