2017-11-09T11:41:20Z||2017-11-09T11:41:20Z


具体错误一长串:

[ts]
Type '{ style: { color: string; fontSize: string; fontWeight: string; backgroundColor: string; padding:...' is not assignable to type 'DetailedHTMLProps<HTMLAttributes<HTMLSpanElement>, HTMLSpanElement>'.
  Type '{ style: { color: string; fontSize: string; fontWeight: string; backgroundColor: string; padding:...' is not assignable to type 'HTMLAttributes<HTMLSpanElement>'.
    Types of property 'style' are incompatible.
      Type '{ color: string; fontSize: string; fontWeight: string; backgroundColor: string; padding: string; ...' is not assignable to type 'CSSProperties | undefined'.
        Type '{ color: string; fontSize: string; fontWeight: string; backgroundColor: string; padding: 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...'.

代码是:

render() {
const style = {
    color: '#ef9494',
    fontSize: '18px',
    fontWeight: 'bold',
    backgroundColor: '#ef9494',
};
return (
    <span style={style}>{this.props.count}</span>
);

问题出在fontWeight的定义上,fontWeightCSSProperties只能规定某种值出现(属于iteral types),而代码中的bold也确实是对的,但是TypeScript默认会把它认为是string而不是iteral types,所以需要强行转换下React.CSSProperties就OK了。

const style = {
    color: '#ef9494',
    fontSize: '18px',
    fontWeight: 'bold',
    backgroundColor: '#ef9494',
} as React.CSSProperties;