Using Elm and TypeScript Together
This post is about using TypeScript and Elm together in a project.
The Elm framework provides
The TypeScript part
The TypeScript part of the solution serves the following goals:
- Bootstrapping the Elm application.
- Working with Elm ports. The TypeScript part acts as a proxy between the Elm application and external APIs In my case—Microsoft Word and Glvrd, an external proofreading service.
- Including Elm files into the bundle. Referencing the Elm application main file, so it would be included in the single production bundle.
The logic related to Elm is defined in the ElmApp.ts file.
1. Bootstrapping the Elm application
The ElmApp.ts file contains the
startApplication function that starts the Elm application:
The function is called once the Office Add-in is initialized.
2. Working with Elm ports
For each port and the Elm application itself there is a type declaration which allows controlling the data that goes into or comes out of the Elm application:
The Index.ts file contains the actual calls to ports using
subscribe functions of ports.
3. Including Elm files into the bundle
The ElmApp.ts references the main Elm application file
The Elm part
I’ve got one outgoing port
suggestions (receives results of a proofread),
textChanged (notifies that the selected text has changed and provides the new text), and
All the ports logic is defined in the Main.elm file.
Here’s all the code related to ports:
Scaling ports in Elm
I’ve defined ports in the main logic file, and I’ve got a separate port for each action. This is a simple approach, but it doesn’t scale well.
If you’ve got a lot of ports, you might want to move them to a separate file for a better control. Also, you may consider using only two ports—one for all incoming messages and one for all outgoing.
Check The Importance of Ports talk by Murphy Randle for details.