类型“字符串”不可分配给类型“继承”\| “初始” \| “未设置” \| “固定” \| “绝对” \| “静态” \| “亲戚” \| “黏”'

新手上路,请多包涵

我的应用程序中出现以下错误(npm 5.4.2、react 15.4、typescript 2.5.3、webpack 2.2.1、webpack-dev-server 2.4.1)。

这将起作用:

 <div style={{position: 'absolute'}}>working</div>

这不会编译:

 const mystyle = {
    position: 'absolute'
}

<div style={mystyle}>not working</div>

编译错误是:

 ERROR in ./src/components/Resource.tsx
(61,18): error TS2322: Type '{ style: { position: string; }; children: string; }' is not assignable to type 'DetailedHTMLProps<HTMLAttributes<HTMLDivElement>, HTMLDivElement>'.
  Type '{ style: { position: string; }; children: string; }' is not assignable to type 'HTMLAttributes<HTMLDivElement>'.
    Types of property 'style' are incompatible.
      Type '{ position: string; }' is not assignable to type 'CSSProperties'.
        Types of property 'position' are incompatible.
          Type 'string' is not assignable to type '"inherit" | "initial" | "unset" | "fixed" | "absolute" | "static" | "relative" | "sticky"'.
webpack: Failed to compile.

但是有什么区别呢?我可以通过以下方式修复它:

 const mystyle = {
    position: 'absolute' as 'absolute'
}

但这是一个好的解决方案吗?

我对其他样式/css 属性没有这个问题。

我在 github 上发现了一个类似的问题: https ://github.com/Microsoft/TypeScript/issues/11465 但如果理解正确,这是早期版本中的打字稿错误。

任何帮助表示赞赏。

原文由 gfjr 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 865
1 个回答

这是一种解决方法,但没关系。其他一些解决方案是:

 const mystyles = {
   position: 'absolute',
} as React.CSSProperties;

您可以查看此 问题 何时解决。从里程碑来看,我猜大概是 TS 2.6。

原文由 Andy Theos 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题