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)
与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)
打字稿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'
不起作用,虽然fontWeight
accepts "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)
归档时间: |
|
查看次数: |
5294 次 |
最近记录: |