How It Works

The ports and flags in an Elm app (also called JS interop) have a shape to them. You can write that shape out with a TypeScript type to make sure the types match up between your Elm and TypeScript code. You could write a definition like this:

export interface ElmApp {
  ports: {
    interopFromElm: PortFromElm<FromElm>;
    interopToElm: PortToElm<ToElm>;

export type FromElm =
  | { tag: "reportError"; data: { message: string; name: string } }
  | { tag: "tryLogIn"; data: null };

export type ToElm =
  | {
      tag: "onAuthenticated";
      data: { isPro: boolean; user: { avatarUrl: string } };
  | { tag: "onNewGeneratedElm"; data: string };

export type Flags = null;

export namespace Main {
  function init(options: { node?: HTMLElement | null; flags: Flags }): ElmApp;

export as namespace Elm;

export { Elm };

export type PortFromElm<Data> = {
  subscribe(callback: (fromElm: Data) => void): void;

export type PortToElm<Data> = { send(data: Data): void };

This is great because now we can safely wire up our Elm application and use ports to send and receive data! But if we wrote it by hand, then it's error prone and likely to get out of date.

That's exactly what elm-ts-interop is designed to help with. This is the workflow to generate a TypeScript Declaration similar to the example above:

  • You maintain a file InteropDefinitions.elm with Encoders/Decoders for your Flags and Ports
  • These Encoders/Decoders use elm-ts-json so they have type information that lets elm-ts-interop sync them to a TypeScript Declaration
  • Run the elm-ts-interop command-line tool to generate types from your Ports and Flags in InteropDefinitions.elm