Using table-layout property with React and TypeScript was giving a type error like below:

ERROR in /var/jenkins/workspace/dev/resources/packages/sites/table.tsx
[tsl] ERROR in /var/jenkins/workspace/dev/resources/packages/sites/table.tsx(79,25)
      TS2322: Type '{ padding: number; width: string; margin: string; tableLayout: string; }' is not assignable to type 'CSSProperties'.
  Types of property 'tableLayout' are incompatible.
    Type 'string' is not assignable to type 'TableLayout'.

This was the styling code:

const getListStyle = () => ({
    padding: 8,
    width: '100%',
    margin: '0px auto',
    tableLayout: 'auto',
});

React/Typescript JSX code:

<table style={getListStyle()}>
    <Header />
    <Body />
</table>

For some reason, table-layout doesn’t seem to accept string values. Although, as per the doc, it should be accepted.

This is the full typescript error reported by the IDE on the style attribute:

TS2322: Type ‘{ padding: number; width: string; margin: string; tableLayout: string; }’ is not assignable to type ‘CSSProperties’.   Types of property ‘tableLayout’ are incompatible.     Type ‘string’ is not assignable to type ‘TableLayout’. index.d.ts(1765, 9): The expected type comes from property ‘style’ which is declared here on type ‘DetailedHTMLProps, HTMLTableElement>’

The fix was to simply add the return type CSSProperties explicity like this:

const getListStyle = (): CSSProperties => ({
    padding: 8,
    width: '100%',
    margin: '0px auto',
    tableLayout: 'auto',
});

Leave a Reply

Your email address will not be published. Required fields are marked *