Try Install Learn Blog API Packages GitHub
Pages

Records

Records are data structures that have a fixed set of keys.

You can define a record type with the record keyword:

record User {
  email : String,
  name : String,
  id : Number
}

Records cannot have types which have type variables.

Literal

The easiest way to create a record is with a record literal:

{
  email: "john@doe.com",
  name: "John Doe",
  id: 1
}

Constructors

For each record a constructor function is available with the same name:

record User {
  name : String,
  age : Number,
  active : Bool,
}

User("John Doe", 32, true) == {
  name: "John Doe",
  active: true,
  age: 32
}

The order of the parameters are in the same as the order the fields.

This function can be partially applied:

record User {
  name : String,
  age : Number,
  active : Bool,
}

User("John Doe", 32)(true) == {
  name: "John Doe",
  active: true,
  age: 32
}

Nested records

Records can be nested in each other, using nested type definitions.

record Position {
  x : Number,
  y : Number
}

record Entity {
  position : Position,
  id : String
}

Creating a nested record is straightforward:

let entity =
  {
    position: {
      x: 0,
      y: 0
    },
    id: "0"
  }

Working with records

Records can be created like this:

{
  email: "john.doe@gmail.com",
  name: "John Doe",
  id: 0
}

You can create a new record by copying from an existing one and changing only some of the fields, like this:

let user =
  {
    email: "john.doe@gmail.com",
    name: "John Doe",
    id: 0
  }

let updatedUser =
  { user | name: "Stuart" }

{
  email: "john.doe@gmail.com",
  name: "Stuart",
  id: 0
}

Trying to set fields to a record which doesn't have it in its definition will raise an error.