'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
Solution 1:[1]
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;
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Ryan Garde |