Dati tipizzati
type dichiara la struttura di alcuni dati, come la risposta di un'API. I dati che vi passano attraverso vengono verificati e trasformati in un record: una mappa che conosce il proprio tipo, così l'editor completa i suoi campi e un errore di battitura come $repo.stras viene intercettato. I campi possono anche essere email, password, handle, uuid o regex, e i tipi possono aggiungere regole ad altri tipi o unirsi a essi. Vedi Tipi e validazione.
Un tipo è un blocco con un campo per riga, 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 legge il campo da una chiave con un altro nome, e owner: User è un altro tipo, quindi anche i dati annidati vengono verificati e trasformati in un record User. Repo(data) mappa una mappa, una lista di mappe o testo JSON.
Usa $.name per cercare un valore nell'ambito corrente. Risolve lo stesso nome di $name, incluso un parametro di funzione, una variabile locale o un campo di componente.
Firme dei metodi
Un tipo può dichiarare un metodo senza scriverne il corpo: termina la riga fn con ; dove andrebbero => o { }. Quella riga è una firma di metodo, e un altro tipo che extends questo deve implementarlo. Un ? dopo il nome del metodo, come in fn details?(): string;, rende il metodo opzionale. L'editor e questa documentazione mostrano le righe di firma in corsivo, così le riconosci a colpo d'occhio dai metodi con corpo. Il controllore segnala qualsiasi metodo obbligatorio mancante o discrepanza nei nomi dei parametri, nei tipi dei parametri o nel tipo di ritorno.
<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
}Righe dei campi
Una riga di campo è name[?][: type] [from path] [= default | => value]. Ogni parte è facoltativa tranne il nome. Un campo con un valore e senza tipo può scrivere il valore subito dopo i due punti, layout: ```text ... ``` o symbols: { '#': '#' }, e prende il tipo dal valore:
<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)'
}| Parte | Cosa fa |
|---|---|
: type |
Un tipo integrato (string, int, float, number, bool, date, list, set, map, fn, any, email, password, handle, uuid, regex), un enum, un altro type, T[] per una lista, set(of: T) per un insieme di T. Le regole possono seguire tra parentesi quadre: string(min: 1). Senza di esse il campo accetta qualsiasi valore. |
? dopo il nome |
Il valore può mancare o essere null. Questo è l'unico modo per contrassegnare un campo come facoltativo, in un type, un model, un error e un job: license?: string, non license: string? (KS6014, con una correzione rapida). T? serve per un tipo che non è proprio del campo, come un parametro che può essere null: fn show(repo: Repo?). |
from path |
Dove leggere il valore quando non corrisponde al nome del campo: stargazers_count, owner.login, items[0].name. I dati annidati escono appiattiti. Racchiudi tra virgolette un percorso che contiene spazi. |
= default |
Il valore quando i dati non ne hanno uno. Il campo diventa quindi facoltativo. |
=> value |
Calcola il campo a partire dagli altri campi (sono $name, $stars e così via) invece di leggerlo. |
/// sopra la riga |
Mostrato al passaggio del mouse e nel completamento. |
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).
Un tipo piccolo può anche stare su una riga, con i campi scritti come parametri fn: type Point(fields: [x: int, y: int]). kscript convert lo scrive come blocco.
In XML, un tipo è <type name="Repo"> con un elemento <field name="stars" type="int" from="stargazers_count" /> per ogni riga, oppure un attributo fields="..." per la forma su una riga. Passa gli esempi a XML per vederli.
Dove i dati incontrano un tipo
<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: accetta un tipo: as: Repo, as: int, o as: Repo[] per una lista di questi, scritto come lo scrive una dichiarazione. $repo->type() è 'Repo'. Un record funziona comunque ovunque funzioni una mappa, ma leggere o impostare un campo che il tipo non ha è un errore, e impostare un campo converte il valore nel tipo del campo.
->type() riporta il tipo degli elementi di una lista. [1, 2]->type() restituisce 'number[]', e una lista di record Repo restituisce 'Repo[]'. Le liste miste e le liste vuote senza tipo restituiscono 'any[]'. Usa ->is_a(list) per verificare se un valore è un tipo di lista qualsiasi.
Quando i dati non corrispondono, la mappatura fallisce con un unico errore Shape che elenca ogni problema con il suo percorso 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'.In una catch, $err.problems è una lista di mappe { path, field, message }. Repo->check($data) restituisce quella lista senza generare errori (vuota quando i dati corrispondono), Repo.fields elenca i campi, e Repo->schema() descrive il tipo come JSON Schema.
Tipi da tipi
Un tipo può essere creato a partire da un altro tipo, così un parametro o un campo segue il tipo a cui si riferisce invece di ripeterlo. Quando il tipo cambia, cambia anche tutto ciò che ne deriva, e l'editor completa, collega e verifica i nomi.
| Forma | Cosa fa |
|---|---|
Post.fields |
Uno dei nomi di campo di Post, scritto senza altro: title. Contano i campi propri di un modello (id, le sue chiavi) e le relazioni. |
Post.fields(except: [body]) |
Meno nomi: except: ne esclude alcuni, only: ne mantiene alcuni, relations: false esclude le relazioni e relations: only mantiene solo quelle. |
Post.title |
Il tipo del campo title di Post, con le sue regole. Post.title(max: 80) aggiunge regole in più. |
Order.address.postcode |
Un campo di un campo. Order.lines.item è un elemento del campo lista lines. |
Self.fields, Self.title |
All'interno di un type o di un model, il tipo che si sta dichiarando. |
draft|live |
Una di queste parole, scritta senza altro. |
int|uuid |
Un valore di uno dei due tipi. Una parola che indica un tipo è quel tipo; mettila tra virgolette per intendere la parola: card|'email'. |
(draft|live)[] |
Le parentesi raggruppano un'unione, qui per creare una lista di essa. |
<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 }"Un valore che non corrisponde viene segnalato come qualsiasi argomento tipizzato, elencando tutti i nomi che potrebbe essere:
'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'.Anche le opzioni integrate sono tipizzate allo stesso modo, e il passaggio del mouse, l'aiuto sulla firma e il riferimento mostrano il tipo di ciascuna:
- Il
hidden:e ilguarded:di un modello accettanoSelf.fields[], ekey:accettaSelf.fields.unique:eindex:accettano(Self.fields|Self.fields[])[], che è un nome o un gruppo di nomi. - Il
unique_by:di un job accettaSelf.fields[]. - Il
ModelUpdatedifields:accettamodel.fields[], cioè i campi del modello che il suomodel:nomina. - Il
Index(columns:)di una migrazione accetta i campi della sua tabella. - I metodi indicano i campi del ricevitore allo stesso modo:
$post->is_dirty(title)accettaSelf.fields,->pick([title, views])e->omit([body])su un record accettanoSelf.fields[], e$posts->pluck(title)o->pluck([title, views])su una lista di record accettanoSelf.fields|Self.fields[]. Un nome che il ricevitore non ha è un errore con un suggerimento. - Le opzioni con poche parole fisse sono unioni di parole:
Document(template: plain|paper|report|letter|invoice),->sort(by:, order?: asc|desc), eResource(only:), che accetta(index|store|show|update|destroy)[]. Una parola che è anche il nome di un tipo viene messa tra virgolette nel tipo, come inechodiformat: text|'json'|'markdown', ma la si scrive senza altro:format: json.
Un campo di modello scritto status: draft|live viene memorizzato come colonna enum del database.
In un gruppo one-of, un | prima dei due punti separa i nomi e un | dopo di essi indica un'unione: id|slug: int|uuid accetta id: o slug:, cioè un int o un uuid. In un gruppo i cui membri hanno tipi diversi, un | seguito da name: inizia il membro successivo: (as: draft|live | template: Template).