Exhaustive Ports

  1. 1. What Is elm-ts-interop?
    2:57
  2. 2. Setup
    2:10
  3. 3. Flags
    2:52
  4. 4. FromElm Ports
    5:44
  5. 5. Encoding Custom Types
    9:54
  6. 6. Exhaustive Ports
    6:30
  7. 7. ToElm Ports
    11:10
  8. 8. Migrating to Pro
    9:32

Chapter Notes

  • We add a variant to our InteropDefinitions.FromElm type

Wiring in a new FromElm variant#

Add a variant to our FromElm

We now have an inexhaustive case expression in our fromElm Encoder.

To handle the additional variant in our Encoder, the steps are:

  • Add a parameter, we can call it vAttemptLogIn (v is short for variant). This parameter will be an encoder that we can use in our case expression.
  • Use vAttemptLogIn for the AttemptLogIn record -> clause in our case expression
  • Add another |> TsEncode.variantTagged to the pipeline (this is the Encoder we get as the vAttemptLogIn parameter).

All the code together looks like:

fromElm : Encoder FromElm
fromElm =
    TsEncode.union
        (\vAlert vAttemptLogIn value ->
            case value of
                Alert string ->
                    vAlert string

                AttemptLogIn record ->
                    vAttemptLogIn record
        )
        |> TsEncode.variantTagged "alert"
            (TsEncode.object
                [ required "message" (\value -> value.message) TsEncode.string
                , required "logKind" (\value -> value.kind) Log.encoder
                ]
            )
        |> TsEncode.variantTagged "attemptLogIn"
            (TsEncode.object
                [ required "username" (\value -> value.username) TsEncode.string
                ]
            )
        |> TsEncode.buildUnion

Hands on with Encoding Discriminated Unions#

ellie-app fQY3tzjQDRRa1

Handle the new variant in TypeScript#

The fromElm value we receive in interopFromElm.subscribe is a TypeScript Discriminated Union.

Set up ESLint to catch inexhaustive switch statements#