typescript 类型 'string' 不可分配给类型 '"inherit" | “初始” | “未设置” | “固定” | “绝对” | “静态” | “相对” | “黏”'

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/46710747/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 04:57:53  来源:igfitidea点击:

Type 'string' is not assignable to type '"inherit" | "initial" | "unset" | "fixed" | "absolute" | "static" | "relative" | "sticky"'

reactjstypescriptwebpack

提问by gfjr

I get the following error in my application (npm 5.4.2, react 15.4, typescript 2.5.3, webpack 2.2.1, webpack-dev-server 2.4.1).

我在我的应用程序中收到以下错误(npm 5.4.2,react 15.4,typescript 2.5.3,webpack 2.2.1,webpack-dev-server 2.4.1)。

This will work:

这将起作用:

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

This will not compile:

这不会编译:

const mystyle = {
    position: 'absolute'            
} 

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

The compile error is:

编译错误是:

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.

But what't the difference? I can fix it with:

但有什么区别呢?我可以用以下方法修复它:

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

but is this a good solution?

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

I don't have this problem with other style/css properties.

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

I found a similar problem on github: https://github.com/Microsoft/TypeScript/issues/11465but if understand it right, it was a typescript bug in an ealier version.

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

Any help appreciated.

任何帮助表示赞赏。

回答by Andy Theos

This is a workaround, but it is alright. Some other solution is:

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

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

You can check back when this issuewill be solved. Around TS 2.6 i guess, judging by milestones.

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

回答by superluminary

Use the React.CSSProperties type:

使用 React.CSSProperties 类型:

import React, { CSSProperties } from "react";

const myStyles: CSSProperties = {
  position: 'absolute',
}

Then just use the style as normal:

然后像往常一样使用样式:

<div style={myStyles} />