Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle Typescript Generics when using styled function from '@mui/material/styles'

import Table,{TableProps} from 'my/table/path'

const StyledTable = styled(Table)({
  ...my styles
})

const AnotherTable = <T, H>(props: TableProps<T, H>) => {
  return <StyledTable {...props} />
}

This is my error message:

Types of parameters 'item' and 'item' are incompatible.
          Type 'unknown' is not assignable to type 'T'.
            'unknown' is assignable to the constraint of type 'T', but 'T' could be instantiated with a different subtype of constraint 'unknown'.

It seems that my generic was not carried over when using styled because when I do it like this:

const AnotherTable = <T, H>(props: TableProps<T, H>) => {
  return <Table {...props} />
}

it does not return any error and my generics are working

like image 562
Ryan Garde Avatar asked Feb 06 '26 07:02

Ryan Garde


1 Answers

I solved it. Basically all I did was explicitly infer the type after it was created.

const StyledTable = styled(Table)({
  ...my styles
}) as typeof Table;
like image 171
Ryan Garde Avatar answered Feb 09 '26 09:02

Ryan Garde



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!