Typed data
type declares the shape of some data, such as an API response. Data that passes through it is checked and turned into a record: a map that knows its type, so the editor completes its fields and a typo like $repo.stras is caught. Fields can also be email, password, handle, uuid or regex, and types can add rules to other types or join them. See Types and validation.
A type is a block with one field per line, name: type:
<type name="User">
<field name="login" type="string" />
<field name="id" type="int" />
</type>
<type name="Repo">
<field name="name" type="string" />
<field name="stars" type="int" from="stargazers_count" />
<field name="owner" type="User" />
</type>
<let name="repo" value="Repo({ name: 'kscript', stargazers_count: 12, owner: { login: 'kyle', id: 1 } })" />
<echo>{ $repo.name } has { $repo.stars } stars, owned by { $repo.owner.login }</echo>type User {
login: string
id: int
}
type Repo {
name: string
stars: int from stargazers_count
owner: User
}
$repo = Repo({ name: 'kscript', stargazers_count: 12, owner: { login: 'kyle', id: 1 } })
echo "{ $repo.name } has { $repo.stars } stars, owned by { $repo.owner.login }"stars: int from stargazers_count reads the field from a key with another name, and owner: User is another type, so the nested data is checked and turned into a User record too. Repo(data) maps a map, a list of maps or JSON text.
Use $.name to look up a value in the current scope. It resolves the same name as $name, including a function parameter, local variable or component field.
Method signatures
A type may declare a method without writing its body: end the fn line with ; where the => or { } would go. That line is a method signature, and another type that extends this one must implement it. A ? after the method's name, as in fn details?(): string;, makes the method optional. The editor and these docs show signature lines in italics, so you can tell them from methods with a body at a glance. The checker reports any missing required method or mismatch in its parameter names, parameter types, or return type.
<type name="Summary">
<fn name="label" params="prefix: string" returns="string" signature=";" />
<fn name="details" optional="?" returns="string" signature=";" />
</type>
<type name="NoteSummary" extends="Summary">
<field name="title" type="string" />
<fn name="label" params="prefix: string" returns="string" value="$prefix + .title" />
</type>type Summary {
fn label(prefix: string): string;
fn details?(): string;
}
type NoteSummary extends Summary {
title: string
fn label(prefix: string): string => $prefix + .title
}Field lines
A field line is name[?][: type] [from path] [= default | => value]. Each part is optional except the name. A field with a value and no type may write the value straight after the colon, layout: ```text ... ``` or symbols: { '#': '#' }, and takes its type from the value:
<enum name="Visibility" values="public, private, internal" />
<type name="Repo" description="A GitHub repository.">
<field name="name" type="string" />
<field name="stars" type="int" from="stargazers_count" description="How many people starred it." />
<field name="owner" type="User" />
<field name="owner_name" type="string" from="owner.login" />
<field name="topics" type="string[]" default="[]" />
<field name="license?" type="string" from="license.name" />
<field name="visibility" type="Visibility" />
<field name="updated" type="date" from="updated_at" />
<field name="label" value="$name + ' (' + $stars + ' stars)'" />
</type>enum Visibility { public, private, internal }
/// A GitHub repository.
type Repo {
name: string
/// How many people starred it.
stars: int from stargazers_count
owner: User
owner_name: string from owner.login
topics: string[] = []
license?: string from license.name
visibility: Visibility
updated: date from updated_at
label => $name + ' (' + $stars + ' stars)'
}| Part | What it does |
|---|---|
: type |
A built-in (string, int, float, number, bool, date, list, map, fn, any, email, password, handle, uuid, regex), an enum, another type, T[] for a list. Rules can follow in brackets: string(min: 1). Without it the field takes any value. |
? after the name |
The value can be missing or null. This is the one way to mark an optional field, in a type, a model, an error and a job: license?: string, not license: string? (KS6014, with a quick fix). T? is for a type that isn't a field's own, such as a parameter that may be null: fn show(repo: Repo?). |
from path |
Where to read the value when it isn't the field's name: stargazers_count, owner.login, items[0].name. Nested data comes out flat. Quote a path that has spaces. |
= default |
The value when the data has none. The field is then optional. |
=> value |
Works the field out from the other fields (they are $name, $stars and so on) instead of reading it. |
/// above the line |
Shown on hover and in completion. |
The type itself takes options in brackets: type Repo(extra: error) { … }. extra says what happens to keys the type doesn't list: drop (the default), keep or error. path: "data/repo.json" takes the fields from a saved sample of the data: objects become nested types, and keys only some list items have become optional. Lines in the block replace the sampled fields they name. Types can refer to each other in any order and to themselves, and top-level types are exported to scripts that import the file. In a project, give each type its own file (types/repo.kscript, types/owner.kscript) and import the ones it uses: import "owner.kscript" at the top of types/repo.kscript (see One type per file).
A small type can also go on one line, with the fields written like fn parameters: type Point(fields: [x: int, y: int]). kscript convert writes it as a block.
In XML, a type is <type name="Repo"> with a <field name="stars" type="int" from="stargazers_count" /> element for each line, or a fields="..." attribute for the one-line form. Switch the examples to XML to see them.
Where data meets a type
<let name="repo" value="@api($url, as: Repo)" /> <!-- KScript.Net: ->check()->convert(from: json, as: Repo) -->
<let name="repos" value="@read_json(./repos.json, as: Repo)" /> <!-- KScript.IO; a list maps item by item -->
<let name="user" value="$text->convert(from: json, as: User)" />
<set name="user" value="User($data)" /> <!-- a map, a list or JSON text -->
<let name="repo" type="Repo" value="$data" /> <!-- also on const and plain assignment -->
<fn name="show" params="repo: Repo, tags: string[]">
<!-- … -->
</fn>$repo = @api($url, as: Repo) // KScript.Net: ->check()->convert(from: json, as: Repo)
$repos = @read_json(./repos.json, as: Repo) // KScript.IO; a list maps item by item
$user = $text->convert(from: json, as: User)
$user = User($data) // a map, a list or JSON text
$repo: Repo = $data // also on const and plain assignment
fn show(repo: Repo, tags: string[]) {
// …
}as: takes a type: as: Repo, as: int, or as: Repo[] for a list of them, written as a declaration writes it. $repo->type() is 'Repo'. A record still works everywhere a map does, but reading or setting a field the type doesn't have is an error, and setting a field converts the value to the field's type.
->type() reports a list's element type. [1, 2]->type() returns 'number[]', and a list of Repo records returns 'Repo[]'. Mixed lists and untyped empty lists return 'any[]'. Use ->is_a(list) to test whether a value is any kind of list.
When the data doesn't fit, mapping fails with one Shape error that lists every problem with its JSON path:
The response from https://api.github.com/... doesn't fit Repo (2 problems):
$.stargazers_count: needs an int, but got the string 'lots'.
$.visibility: must be a Visibility (public, private, internal), but got the string 'secret'.In a catch, $err.problems is a list of { path, field, message } maps. Repo->check($data) returns that list without throwing (empty when the data fits), Repo.fields lists the fields, and Repo->schema() describes the type as JSON Schema.
Types from types
A type can be made from another type, so a parameter or field follows the type it's about instead of repeating it. When the type changes, everything made from it changes too, and the editor completes, links and checks the names.
| Form | What it is |
|---|---|
Post.fields |
One of Post's field names, written bare: title. A model's own fields (id, its keys) and relations count. |
Post.fields(except: [body]) |
Fewer names: except: drops some, only: keeps some, relations: false drops relations and relations: only keeps only them. |
Post.title |
The type of Post's title field, with its rules. Post.title(max: 80) adds rules on top. |
Order.address.postcode |
A field of a field. Order.lines.item is one item of the list field lines. |
Self.fields, Self.title |
Inside a type or model, the type being declared. |
draft|live |
One of these words, written bare. |
int|uuid |
A value of either type. A word that names a type is the type; quote it to mean the word: card|'email'. |
(draft|live)[] |
Brackets group a union, here to make a list of it. |
<type name="Post">
<field name="title" type="string(min: 3)" />
<field name="body" type="string" />
<field name="tags" type="string[]" />
<field name="sorted_by" type="Self.fields" default="'title'" />
</type>
<fn name="column" params="by: Post.fields(except: [tags])" value=""sorted by { $by }"" />
<fn name="retitle" params="title: Post.title" value=""renamed to { $title }"" />
<fn name="tag" params="tag: Post.tags.item" value=""tagged { $tag }"" />
<fn name="publish" params="post: Post, as: draft|live = 'live'" value=""{ $post.title } is { $as }"" />
<fn name="find" params="id: int|uuid" value=""found { $id }"" />
<let name="post" value="Post({ title: 'Hello', body: '…', tags: [] })" />
<echo>{ @column(by: body) }, { @retitle('Hello again') }, { @tag('news') }</echo>
<echo>{ @publish($post, as: draft) }, { @find(42) }, { $post.sorted_by }</echo>type Post {
title: string(min: 3)
body: string
tags: string[]
sorted_by: Self.fields = 'title'
}
fn column(by: Post.fields(except: [tags])) => "sorted by { $by }"
fn retitle(title: Post.title) => "renamed to { $title }"
fn tag(tag: Post.tags.item) => "tagged { $tag }"
fn publish(post: Post, as: draft|live = 'live') => "{ $post.title } is { $as }"
fn find(id: int|uuid) => "found { $id }"
$post = Post({ title: 'Hello', body: '…', tags: [] })
echo "{ @column(by: body) }, { @retitle('Hello again') }, { @tag('news') }"
echo "{ @publish($post, as: draft) }, { @find(42) }, { $post.sorted_by }"A value that doesn't fit is reported the way any typed argument is, listing every name it could be:
'titel' isn't one of Post's fields. Use title, body, tags or sorted_by.
'drafty' isn't one of these words. Did you mean draft? Use draft or live.
The 'id' argument of @find() doesn't fit int|uuid: needs int or uuid, but got the string 'nope'.Built-in options are typed the same way, and hover, signature help and the reference show each one's type:
- A model's
hidden:andguarded:takeSelf.fields[], andkey:takesSelf.fields.unique:andindex:take(Self.fields|Self.fields[])[], which is a name or a group of names. - A job's
unique_by:takesSelf.fields[]. ModelUpdate'sfields:takesmodel.fields[], the fields of the model itsmodel:names.- A migration's
Index(columns:)takes the fields of its table. - Methods name the receiver's fields the same way:
$post->is_dirty(title)takesSelf.fields,->pick([title, views])and->omit([body])on a record takeSelf.fields[], and$posts->pluck(title)or->pluck([title, views])on a list of records takesSelf.fields|Self.fields[]. A name the receiver doesn't have is an error with a suggestion. - Options with a few fixed words are word unions:
Document(template: plain|paper|report|letter|invoice),->sort(by:, order?: asc|desc), andResource(only:), which takes(index|store|show|update|destroy)[]. A word that is also a type's name is quoted in the type, as inecho'sformat: text|'json'|'markdown', but you still write it bare:format: json.
A model field written status: draft|live is stored as a database enum column.
In a one-of group, a | before the colon separates the names and a | after it is a union: id|slug: int|uuid takes id: or slug:, either an int or a uuid. In a group whose members have different types, a | followed by name: starts the next member: (as: draft|live | template: Template).