Skip to content

Basic Types

In this lesson, we will cover some basic types. There are certainly many more types, but for this lesson, we will focus on just a few.

This example is simple and almost too trivial, but the point of this lesson is not to show something practical but illustrate basic typing. Each option will have a specific type declared and any configuration values must be of that declared type. For this lesson, we will not investigate setting bad config values. We will will have declared options, a configuration that is correct, and check that our output is exactly as we expect.

In the options.nix file, we have declared boolean, enumeration, integer, and string options.

options.nix
{lib, ...}: let
  inherit (lib) types;
in {
  options = {
    exBool = lib.mkOption {
      type = types.bool;
      description = "My example boolean.";
    };
    exEnum = lib.mkOption {
      type = types.enum ["left" "right"];
      description = "My example enumeration.";
    };
    exInt = lib.mkOption {
      type = types.int;
      description = "My example integer.";
    };
    exStr = lib.mkOption {
      type = types.str;
      description = "My example string.";
    };
  };
}

In the config.nix file, we have declared values for all these options.

config.nix
{...}: {
  config = {
    exBool = true;
    exInt = 42;
    exEnum = "left";
    exStr = "hello";
  };
}

In the eval.nix file, we evaluate our options and config and have it return the config values.

eval.nix
{pkgs}:
(
  pkgs.lib.evalModules {
    modules = [
      ./options.nix
      ./config.nix
    ];
  }
)
.config

In the run.sh file, we evaluate the eval.nix file and have it print out a nicely formatted version of the configuration.

run.sh
nix eval -f eval.nix \
    --apply 'x: x {pkgs = import <nixpkgs> {};}' \
    --json | nix run nixpkgs#jq -- .

If you execute the run file (./run.sh), you should see an output that matches what we have configured.

{
  "exBool": true,
  "exEnum": "left",
  "exInt": 42,
  "exStr": "hello"
}