类型化数据
type 用于声明某些数据(例如 API 响应)的结构。流经它的数据会经过检查并转换为记录:一种知道自身类型的映射,因此编辑器可以补全其字段,而像 $repo.stras 这样的拼写错误会被捕获。字段还可以是 email、password、handle、uuid 或 regex,类型也可以为其他类型添加规则或与之合并。参见 类型与验证。
类型是一个代码块,每行一个字段,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 从名称不同的键中读取字段,owner: User 是另一个类型,因此嵌套的数据也会经过检查并转换为 User 记录。Repo(data) 将映射、映射列表或 JSON 文本进行映射。
使用 $.name 在当前作用域中查找某个值。它解析名称的方式与 $name 相同,包括函数参数、局部变量或组件字段。
方法签名
类型可以声明一个方法而不编写其方法体:在 fn 行末尾使用 ; 代替 => 或 { } 的位置。这一行即为方法签名,而 extends 此类型的其他类型必须实现它。方法名后的 ?(如 fn details?(): string;)会使该方法变为可选。编辑器和本文档会以斜体显示签名行,便于一眼区分它们与带方法体的方法。检查器会报告任何缺失的必需方法,或其参数名称、参数类型、返回类型不匹配的情况。
<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
}字段行
字段行的格式为 name[?][: type] [from path] [= default | => value]。除名称外,每个部分都是可选的。带值但不带类型的字段可以在冒号后直接书写值,如 layout: ```text ... ``` 或 symbols: { '#': '#' },并从该值推断其类型:
<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)'
}| 部分 | 作用 |
|---|---|
: 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. |
名称后的 ? |
该值可以缺失或为 null。这是将字段标记为可选的唯一方式,适用于 type、model、error 和 job:使用 license?: string,而不是 license: string?(KS6014,附带快速修复)。T? 适用于并非字段自身类型的情况,例如可能为 null 的参数:fn show(repo: Repo?)。 |
from path |
当值不在字段名对应的位置时,从何处读取:stargazers_count、owner.login、items[0].name。嵌套数据会被展平。包含空格的路径需加引号。 |
= default |
数据中没有该值时使用的值。此时字段为可选。 |
=> value |
根据其他字段(即 $name、$stars 等)计算该字段,而不是读取它。 |
行上方的 /// |
在悬停和补全时显示。 |
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).
小型类型也可以写在一行中,字段的写法类似 fn 参数:type Point(fields: [x: int, y: int])。kscript convert 则将其写成代码块形式。
在 XML 中,类型是 <type name="Repo">,每行对应一个 <field name="stars" type="int" from="stargazers_count" /> 元素;单行形式则使用 fields="..." 属性。将示例切换为 XML 即可查看。
数据与类型的交汇处
<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: 接受一个类型:as: Repo、as: int,或用 as: Repo[] 表示其列表,写法与声明相同。$repo->type() 为 'Repo'。记录在任何能用映射的地方仍然有效,但读取或设置该类型不具备的字段会报错,设置字段时会将值转换为该字段的类型。
->type() 返回列表的元素类型。[1, 2]->type() 返回 'number[]',由 Repo 记录组成的列表返回 'Repo[]'。混合列表和无类型的空列表返回 'any[]'。使用 ->is_a(list) 判断某个值是否为任意类型的列表。
当数据不符合要求时,映射会失败,并抛出一个 Shape 错误,列出每个问题及其 JSON 路径:
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'.在 catch 中,$err.problems 是一个由 { path, field, message } 映射组成的列表。Repo->check($data) 在数据符合时返回该列表(否则为空),且不会抛出异常;Repo.fields 列出各字段;Repo->schema() 以 JSON Schema 的形式描述该类型。
由类型派生类型
一个类型可以由另一个类型派生而来,这样参数或字段就能跟随其所代表的类型,而无需重复声明。当原类型发生变化时,由它派生的所有类型也随之变化,编辑器会对名称进行补全、链接并检查。
| 表单 | 它是什么 |
|---|---|
Post.fields |
Post 的某个字段名,直接写出:title。模型自身的字段(id 及其键)和关系都可以使用。 |
Post.fields(except: [body]) |
更少的名称:except: 去掉部分名称,only: 保留部分名称,relations: false 去掉关系,relations: only 仅保留关系。 |
Post.title |
Post 的 title 字段的类型及其规则。Post.title(max: 80) 在此基础上添加规则。 |
Order.address.postcode |
字段的字段。Order.lines.item 是列表字段 lines 中的一项。 |
Self.fields, Self.title |
在 type 或 model 内部,指正在声明的类型。 |
draft|live |
其中一个词,直接写出。 |
int|uuid |
任一类型的值。表示类型的名称即为该类型;若要表示这个词本身,请加引号:card|'email'。 |
(draft|live)[] |
方括号用于对联合类型分组,这里用于构成其列表。 |
<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 }"无法匹配的值会像其他任何带类型参数一样报告,并列出它可能是的所有名称:
'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'.内置选项同样带有类型,悬停提示、签名帮助和参考文档都会显示每个选项的类型:
- 模型的
hidden:和guarded:接受Self.fields[],key:接受Self.fields。unique:和index:接受(Self.fields|Self.fields[])[],即一个名称或一组名称。 - 作业的
unique_by:接受Self.fields[]。 ModelUpdate的fields:接受model.fields[],即其model:所指定模型的字段。- 迁移的
Index(columns:)接受其表的字段。 - 方法同样以这种方式引用接收者的字段:
$post->is_dirty(title)接受Self.fields,记录上的->pick([title, views])和->omit([body])接受Self.fields[],记录列表上的$posts->pluck(title)或->pluck([title, views])接受Self.fields|Self.fields[]。接收者没有的名称会报错,并给出建议。 - 带有少量固定词的选项即为词联合类型:
Document(template: plain|paper|report|letter|invoice)、->sort(by:, order?: asc|desc),以及接受(index|store|show|update|destroy)[]的Resource(only:)。若某个词同时也是某个类型的名称,则在该类型中加引号,如echo的format: text|'json'|'markdown',但仍直接写出:format: json。
写作 status: draft|live 的模型字段会存储为数据库的枚举列。
在一组 one-of 中,冒号前的 | 用于分隔名称,冒号后的 | 表示联合类型:id|slug: int|uuid 接受 id: 或 slug:,即整数或 uuid。在成员类型各不相同的组中,| 后接 name: 表示开始下一个成员:(as: draft|live | template: Template)。