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).
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.
I found a similar problem on github: https://github.com/Microsoft/TypeScript/issues/11465 but if understand it right, it was a typescript bug in an ealier version.
Any help appreciated.
The "Type 'string' is not assignable to type" TypeScript error occurs when we try to assign a value of type string to something that expects a different type, e.g. a more specific string literal type or an enum. To solve the error use a const or a type assertion.
The "Type 'string | undefined' is not assignable to type string" error occurs when a possibly undefined value is assigned to something that expects a string . To solve the error, use the non-null assertion operator or a type guard to verify the value is a string before the assignment.
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 issue will be solved. Around TS 2.6 i guess, judging by milestones.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With