KScript docs
EN

Types and validation

Introduction

KScript has built-in types for text that means something, called native types: email, url, ip, country, duration, color and two dozen more. A value of one of these types is checked and tidied when it is made, and it keeps working as text. You can also make your own types from them. A refinement type adds rules to one type, such as type Age with [int] { min: 0; max: 150 }. A joined type puts other types together, such as type Admin with [User, Auditable]. A value that passes a type's rules can be used anywhere that type is expected.

<type name="Username" with="handle" max="16" not="[@admin, @root]">
  <validate test="not $value.name->starts_with('_')" message="A username cannot start with _" />
</type>

<fn name="greet" params="user: Username" value="'Hi ' + $user.name" />

<echo value="@greet(@Joan)" />
<try>
  <echo value="@greet(@admin)" />
  <catch as="err">
    <echo value="$err.message" />
  </catch>
</try>
type Username with [handle] {
  max: 16
  not: [@admin, @root]
  validate: not $value.name->starts_with('_'), 'A username cannot start with _'
}

fn greet(user: Username) => 'Hi ' + $user.name

echo @greet(@Joan)
try {
  echo @greet(@admin)
} catch err {
  echo $err.message
}

The rest of this page covers each native type, the operators they support, values written without quotes, and how to build types of your own from them.

Edit this page on GitHub