Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript error during inline fontWeight style in React

I'm trying to implement this css rule on a td

const boldText = {
    fontWeight: 'bold'
}

<td style={boldText}>Content</td>

But it's throwing the following error:

[ts]
Type '{ style: { fontWeight: string; }; children: string; }' is not assignable to type 'DetailedHTMLProps<TdHTMLAttributes<HTMLTableDataCellElement>, HTMLTableDataCellElement>'.
  Type '{ style: { fontWeight: string; }; children: string; }' is not assignable to type 'TdHTMLAttributes<HTMLTableDataCellElement>'.
    Types of property 'style' are incompatible.
      Type '{ fontWeight: string; }' is not assignable to type 'CSSProperties'.
        Types of property 'fontWeight' are incompatible.
          Type 'string' is not assignable to type '"bold" | "initial" | "inherit" | "unset" | "normal" | "bolder" | "lighter" | 100 | 200 | 300 | 40...'.
like image 279
blankface Avatar asked Jan 04 '18 00:01

blankface


1 Answers

Typescript can be awfuly silly sometimes. It's inferring the type of fontWeight as a string, even though it could narrow it to its exact literal. You can just cast it as itself to fix this:

const boldText = {
    fontWeight: 'bold' as 'bold'
}

<td style={boldText}>Content</td>

These days you can also use the new as const declaration at the end of your literals for the same effect:

const boldText = {
    fontWeight: 'bold'
} as const;

<td style={boldText}>Content</td>

And finally, you can always provide an explicit type to the object when you declare it:

const boldText: React.CSSProperties = {
    fontWeight: "bold"
};

<td style={boldText}>Content</td>
like image 58
CRice Avatar answered Sep 21 '22 09:09

CRice