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...'.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With