TS 2540: Cannot assign to style because it is a read-only property

oli*_*ren 24 typescript

I am creating a textarea element in my TSX markup, and the TS typechecker in Vim complains 2540: Cannot assign to style because it is a read-only property. Having textarea.style be read-only is a bit weird, given that it can be written to ...

维姆错误 How can I make the error message disappear? Should I cast the input variable in my code to something else?

gig*_*gnu 27

我通过使用解决了它:

input.setAttribute('style', 'white-space: pre; position: absolute; left: -9999px;');
Run Code Online (Sandbox Code Playgroud)

显然“TypeScript 在 Element 上没有样式属性。” 正如相关 Stackoverflow 答案中提到的那样。


小智 6

或者你可以使用input.style.cssText

input.style.cssText = "white-space:pre; position:absolute; left:-9999px;";


oli*_*ren 1

Apparently, I already had the answer ...

Saying the input variable is the specific type made it work.

const input: HTMLTextAreaElement = document.createElement('textarea')                                                                                                   
const currentTarget = e.currentTarget as HTMLDivElement    
Run Code Online (Sandbox Code Playgroud)

This is probably because createElement can create all kinds of elements and Typescript has no way of knowing which, as it is based on the input string. So you need to say what it is returning.