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

Viewed 468
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

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;
Related