Dieter's Words

Stimulus and TypeScript

Published  

Currently there is an issue with TypeScript and how stimulus uses values and targets. In your controller you would normally just use a target like:

this.someTarget

However this causes issues with TypeScript as it doesn't know the type so things go wonky so you add something like:

const someTarget: Element

But that causes other issues with Babel as it transforms the code to only have a getter and no setter. Until stimulus comes up with a solution there is a workaround and you can use declares to do it like so:

declare someTarget: Element

This tells TypeScript that there is a type on this object but doesn't add a property, and now another error crops up with how Babel is used with Rails and we need to make a change to how TypeScript is processed. It is fairly simple so we go into our Babel config and add the following to your plugins:

["@babel/plugin-transform-typescript", { 'allExtensions': true, 'isTSX': true, 'allowDeclareFields': true }],

Now declare fields are parsed correctly and removed from the final code allowing TypeScript to be happy and not complain about how Stimulus targets and values are typed. Happy coding.

Dieter Lunn

© DYNABLOGGER.COM
powered by DynaBlogger