型付きデータ
typeは、APIレスポンスなどのデータの形を宣言します。型を通過するデータは検証され、レコードに変換されます。レコードは自身の型を把握したマップなので、エディターがフィールドを補完し、$repo.strasのようなタイプミスを検出できます。フィールドはemail、password、handle、uuid、regexにすることもでき、型は他の型にルールを追加したり、型同士を結合したりできます。型と検証を参照してください。
型は、1行に1フィールドを書くブロックです。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 |
組み込み型(string、int、float、number、bool、date、list、set、map、fn、any、email、password、handle、uuid、regex)、enum、別のtype、リストのT[]、Tの集合のset(of: T)。角かっこでルールを続けられます:string(min: 1)。これを省略すると、フィールドは任意の値を受け付けます。 |
名前の後の? |
値がない場合や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など)から値を計算します。読み取るのではありません。 |
行の上の/// |
ホバーと補完で表示されます。 |
型自体にはかっこ内にオプションを指定できます:type Repo(extra: error) { … }。extraは、型に定義されていないキーの扱いを指定します:drop(デフォルト)、keep、またはerror。path: 'data/repo.json'は、保存されたデータのサンプルからフィールドを取得します。オブジェクトはネストされた型になり、一部のリスト項目にしか存在しないキーは省略可能になります。ブロック内の行は、名前が指定されたサンプルのフィールドを置き換えます。型は任意の順序で互いを参照でき、自分自身も参照できます。トップレベルの型は、そのファイルをimportするスクリプトにエクスポートされます。プロジェクトでは、型ごとに個別のファイル(types/repo.kscript、types/owner.kscript)を用意し、使用する型をimportしてください:types/repo.kscriptの先頭にimport "owner.kscript"を書きます(1ファイルに1型を参照)。
小さな型は1行にまとめることもできます。フィールドはfnの引数のように書きます:type Point(fields: [x: int, y: int])。kscript convertを使うとブロックとして書けます。
XMLでは、型は<type name="Repo">で、各行には<field name="stars" type="int" from="stargazers_count" />要素を、1行形式には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)を使います。
データが型に合わない場合、マッピングは1つの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の1要素です。 |
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)、Resource(only:)は(index|store|show|update|destroy)[]を取ります。型名にもなっている語は型の中で引用符付きになります(例:echoのformat: text|'json'|'markdown')が、書くときは修飾なしでformat: jsonと書きます。
status: draft|liveと書かれたモデルフィールドは、データベースのenum列として保存されます。
one-ofグループでは、コロンの前の|が名前を区切り、コロンの後の|は共用体になります: id|slug: int|uuidはid:またはslug:、つまりintかuuidのどちらかを取ります。メンバーの型が異なるグループでは、|の後にname:が続くと次のメンバーが始まります: (as: draft|live | template: Template)。