使用“@mui/material/styles”中的样式函数时如何处理 Typescript 泛型

Rya*_*rde 9 typescript reactjs material-ui

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

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

const AnotherTable = <T, H>(props: TableProps<T, H>) => {
  return <StyledTable {...props} />
}
Run Code Online (Sandbox Code Playgroud)

这是我的错误消息:

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'.
Run Code Online (Sandbox Code Playgroud)

看来我的通用在使用时没有被继承,styled因为当我这样做时:

const AnotherTable = <T, H>(props: TableProps<T, H>) => {
  return <Table {...props} />
}
Run Code Online (Sandbox Code Playgroud)

它不会返回任何错误,并且我的泛型正在工作

Rya*_*rde 13

我解决了。基本上我所做的就是在创建类型后显式推断类型。

const StyledTable = styled(Table)({
  ...my styles
}) as typeof Table;
Run Code Online (Sandbox Code Playgroud)