Ответ 1
Это обходной путь, но все в порядке. Другое решение:
const mystyles = {
position: 'absolute',
} as React.CSSProperties;
Вы можете проверить, когда будет issue. Вокруг TS 2.6 я думаю, судя по вехам.
В моем приложении появляется следующая ошибка (npm 5.4.2, реакция 15.4, машинопись 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, но если все правильно понять, это была ошибка с машинописью в более ранней версии.
Любая помощь приветствуется.
Это обходной путь, но все в порядке. Другое решение:
const mystyles = {
position: 'absolute',
} as React.CSSProperties;
Вы можете проверить, когда будет issue. Вокруг TS 2.6 я думаю, судя по вехам.
Используйте тип React.CSSProperties:
import React, { CSSProperties } from "react";
const myStyles: CSSProperties = {
position: 'absolute',
}
Тогда просто используйте стиль как обычно:
<div style={myStyles} />