React中内联fontWeight样式期间的Typescript错误

Zer*_*rty 4 typescript reactjs

我正试图在a上实现这个css规则 td

const boldText = {
    fontWeight: 'bold'
}

<td style={boldText}>Content</td>
Run Code Online (Sandbox Code Playgroud)

但它抛出以下错误:

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

CRi*_*ice 15

打字稿有时会非常愚蠢.它推断fontWeight出字符串的类型,即使它可以将其缩小到精确的字面值.你可以把它当作自己来解决这个问题:

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

<td style={boldText}>Content</td>
Run Code Online (Sandbox Code Playgroud)

  • 如果你有很多属性有同样的问题,你也可以将样式对象声明为 **any**,而不是一一修复:```const boldText = { fontWeight: 'bold' } as any;``` (2认同)
  • 这根本不应该是答案。请使用类型!从 React 或 w/e 导入 CSSProperties 并在属性对象上使用它。 (2认同)

Gio*_*gos 6

与CRice 的答案类似,但更通用一些:

type FontWeight = 'normal' | 'bold' | '100' | '200' | '300' | '400' | '500' | '600' | '700' | '800' | '900';

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

<td style={boldText}>Content</td>
Run Code Online (Sandbox Code Playgroud)


kca*_*kca 5

打字稿boldText视为“正常”对象,因此推断boldText.fontWeight为字符串:

const boldText = {
    fontWeight: 'bold' // <-- TS doesn't know more than this is a string
}
Run Code Online (Sandbox Code Playgroud)

代码<td style={boldText}>Content</td>需要CSSProperties,因此无法分配字符串。

为了解决不匹配,你可以告诉 Typescript 对象的类型:

const boldText: CSSProperties = {
    fontWeight: 'bold'
}
Run Code Online (Sandbox Code Playgroud)

更准确地说:

  • 例如color: '#ff0000'会起作用,因为color接受字符串类型的值。
  • fontWeight: 'bold'不起作用,虽然fontWeightaccepts "bold",因为TS在了解CSS上下文之前决定使用类型字符串,而类型字符串与类型“粗体”不一样| “更大胆” | 100 | 200 | ...
const boldText = {
    fontWeight: 'bold'  // <-- TS makes it's decision for type 'string'
    color: '#ff0000'    // <-- TS makes it's decision for type 'string'
}

// TS doesn't complain about color, as color accepts NamedColor | string | ...
// TS only complains about fontWeight, as it accepts only "bold" | "bolder" | 100 | 200 | ...
const TD = <td style={boldText}>Content</td>
Run Code Online (Sandbox Code Playgroud)