Interfaces and unions#
Meta: these align directly with GraphQL interfaces and unions, so users coming from a schema will recognize them. Worth saying that up front to set expectations.
Interfaces and unions work like their GraphQL counterparts, so a schema's interfaces and unions are ordinary Dang types. Both are taken apart with case (see Control flow), and GraphQL values also with inline fragments (see GraphQL interop). One difference: an interface declared in Dang is satisfied by any type of its shape (see Structural: interfaces across schemas).
The examples on this page are live: they share one Dang environment, so later snippets use earlier definitions. Each result is computed and baked in by the docs build — edit a snippet and hit Run ▶ to replay the page in your browser. Blocks that show an error are supposed to fail: the build verifies the failure the same way it verifies the results.
Interfaces#
Declaration#
interface Named {
name: String!
}
Implementation#
type Person implements Named {
name: String!
age: Int!
}
type Company implements Named {
name: String!
size: Int!
}
implements A & Bfor multiple- field types must satisfy the interface (subtyping rules below)
- the built-in
Errorinterface (see Errors:raiseandrescue) is an ordinary interface; user error types implement it
A method satisfies an interface field too. Robot computes its name:
type Robot implements Named {
serial: Int!
name: String! { `unit-${serial}` }
}
greet(n: Named!): String! { `hello, ${n.name}` }
[greet(Person("Ada", 36)), greet(Robot(7))]
Conformance is checked. A missing field, or one whose type doesn't fit, is an error:
type Rock implements Named { weight: Int! }
type Pebble implements Named { name: Int! }
An interface's fields are readable by anyone holding the interface, so a let member can't implement a public interface field (nor can a child interface redeclare a parent's public field with let):
type Secret implements Named { let name: String! = "classified" }
The interface name is also a value: its namespace, not an instance. It can't be passed where an instance is expected, and no type pattern matches it:
greet(Named)
Structural: interfaces across schemas#
An interface declared in Dang is structural: a type with its fields is one of its values, whether or not it says implements. Badge declares nothing, and passes for a Named all the same:
type Badge {
name: String!
issued: Int!
}
greet(Badge("Grace", 1952))
That makes Dang's interfaces the way to write one interface over types from different places: Dang types, and the types of every imported GraphQL schema, none of which can name an interface of yours. The prelude's Error (see Errors: raise and rescue) is one, so a schema's own error type with a message: String! raises and rescues like a Dang error.
The rules are the ones implements checks below — the same fields, public, with types that fit — and a type pattern on the interface matches values of the shape too. A type lacking a field, or hiding it behind let, isn't one:
type Pebble { weight: Int! }
greet(Pebble(3))
What implements adds is a check where the type is declared, and a supertype for good: it pins the types of the fields it conforms with, and lets a list of different implementations merge to the interface. Structural conformance is a question asked where a value meets the interface, and pins nothing. A type that only has the shape doesn't merge with another to the interface (branches of the two widen to a union, as ever); to put them in one list, give one the interface's type:
type Plaque { name: String! }
[(Badge("Ada", 1843) :: Named!), Plaque("Turing")].map { greet(_) }
Interfaces a GraphQL schema declares stay nominal, as GraphQL's are: the server decides which types implement them, and resolves fragments on them by that.
Interface inheritance#
interface Dated { createdAt: String! }
interface Author implements Named {
name: String!
email: String!
}
interface Story implements Named & Dated {
name: String!
createdAt: String!
title: String!
}
A child interface must re-declare every field the parent declares, with compatible types (the same variance rules as type implementations):
interface Label implements Named { text: String! }
A value of the child interface type widens to the parent, and lists do too:
type Essay implements Story {
name: String!
createdAt: String!
title: String!
}
let stories: [Story!]! = [Essay("Ada", "1843", "Notes")]
let everyone: [Named!]! = stories
everyone.map { _.name }
Variance#
Return types may be more specific (covariant). An interface field summary: String (nullable) can be implemented as summary: String! (non-null), but not the other way around:
interface Summarized { summary: String }
type Report implements Summarized { summary: String! = "all good" }
interface Headlined { headline: String! }
type Draft implements Headlined { headline: String }
Argument types may be more general (contravariant): an implementation can accept a nullable argument where the interface wants a non-null one. Extra optional arguments are allowed too:
interface Formatter { format(input: String!): String! }
type Lenient implements Formatter {
format(input: String, width: Int! = 10): String! { (input ?? "").padLeft(width) }
}
Lenient.format("hi") + "|"
- block arguments are arguments too: the implementation's block parameter must accept every block the interface's callers may pass, naming its parameters as the interface's does. An implementation may call its block with something more specific than the interface promises the block, not more general
- list elements are covariant in both nullability and type:
[String!]satisfies[String], and[Dog!]satisfies[Animal!]
Scalar fields are invariant: an ID! field does not satisfy a String! interface field, even though an ID! value can be passed where a String! is wanted (see Enums and scalars):
interface Keyed { key: String! }
type Row implements Keyed { key: ID! }
Generic members#
An interface method can declare type parameters after its name, with bounds, as a function does (see Type parameters, Ordered and Numeric). Callers through the interface pick its types within those bounds:
interface Ranker {
best[a: Ordered](x: a!, y: a!): a!
}
type Highest implements Ranker {
best[a: Ordered](x: a!, y: a!): a! {
if (x < y) { y } else { x }
}
}
pickBest(r: Ranker!): String! { r.best("ant", "bee") }
pickBest(Highest)
An implementation declares the same bounds, or fewer: a method that takes any a takes the Ordered values the interface's callers pass. A bound the interface doesn't declare is an error, since its callers may pass types without it:
type Total implements Ranker {
best[a: Ordered & Numeric](x: a!, y: a!): a! { x + y }
}
So is an implementation that takes less than every type the callers may pick, with or without a type parameter list: a concrete type where the interface has a type variable, or one variable where it has two:
type Initial implements Ranker {
best(x: String!, y: String!): String! { x }
}
A member without arguments is read like a field, so it can't have type variables, declared or not.
Pattern-matching an interface#
describe(n: Named!): String! {
case (n) {
p: Person! => `${p.name}, age ${p.age}`
c: Company! => `${c.name}, ${c.size} people`
fallback: Named! => fallback.name
}
}
[describe(Person("Ada", 36)), describe(Company("Acme", 12)), describe(Robot(7))]
binding: Type!narrows; the binding is typed as the matched concrete/interface type inside the arm- an interface pattern (
n: Named!) matches any implementer — useful as a catch-all after specific types - see Control flow for full
casesemantics; flow typing of the binding is covered in Flow-sensitive narrowing
A pattern must name a type some value of the operand may have. A plain object matches its own type, the interfaces it implements and the unions it belongs to; another object type is an error:
case (Person("Ada", 36)) { c: Company! => c.name }
On a GraphQL interface or union value, type patterns match the object's concrete type, whatever type the field that produced it declares, nullable or not. With the bundled Demo schema (see GraphQL interop), whose favoriteNode is a Node!:
import Demo
case (favoriteNode) {
u: User! => u.name
p: Post! => p.title + " by " + p.author.name
else => "something else"
}
- a GraphQL value that only knows its declared type (like
favoriteNodeabove) costs one small query:caseasks the server for the object'sidand__typename, and the arm binds a handle of the concrete type, loaded by that ID, just like a checked nullable field (Nullable object fields).p.titlethen selects through the loader - no query is sent when there's nothing to learn: without type patterns, for a value whose concrete type is already known (a checked nullable field, a
... on Postnarrowing), or when the first type pattern is satisfied by the declared type itself (n: Node! =>first) - the exception is a value reached through a mutation: asking would re-send the mutation, so it keeps its declared type. Only a pattern that type already satisfies (
n: Node!) can match it; the first type pattern that isn't raisescannot match type pattern Post against a Node reached through mutation …, instead of falling through to a later arm orelse. To discriminate a mutation result, select the fields of every type it may be on the mutation call, which sends it once:Mutation.touchNode(id: "Post:1").{{ ... on Post {{ title }}, ... on User {{ name }} }}, thencaseon that (a selection without a fragment for the value's actual type fails) - value patterns still compare against the original handle, so
case (f) { f => … }matches asf == fdoes (GraphQL interop) - for when to reach for inline fragments instead, see Discriminating
Unions#
Declaration#
type Cat { name: String!; lives: Int! = 9 }
type Dog { name: String!; tricks: [String!]! = [] }
union Pet = Cat | Dog
Members must be object types that exist:
enum Mood { HAPPY GRUMPY }
union Feeling = Cat | Mood
union Aquarium = Cat | Fish
Discriminating#
let pets: [Pet!]! = [Cat("Tom"), Dog("Rex", ["sit", "stay"])]
pets.map { pet =>
case (pet) {
c: Cat! => `${c.name} has ${c.lives} lives`
d: Dog! => `${d.name} knows ${d.tricks.join(" and ")}`
}
}
Covering every member is exhaustive: no else needed, and the result stays non-null. A nullable operand also needs a null => arm. A case that leaves a member out still type-checks, but a value that matches no arm yields null, so the result is nullable. Add else => ... to cover the rest and keep it non-null:
petName(p: Pet!): String! {
case (p) { c: Cat! => c.name }
}
A type that no member is can't be matched:
case (pets[0]!) { p: Person! => p.name }
- GraphQL union values match their concrete type, the same way as interface values (see above), at the cost of the same one small query
- for GraphQL values,
caseand an inline fragment (below) both discriminate, with different tradeoffs:.{{ ... on User {{ name }}, ... on Post {{ title }} }}gets the type and the fields in one round-trip, and works over a list in that same round-trip. The result is a record holding just the selected fieldscasecosts a query to learn the type, then each arm's selections run on their own, but the binding is a full handle: keep chaining off it (u.posts.{{ title }}) or pass it along as an argument- so read fields with fragments, and branch with
casewhen an arm does more with the object than read a few fields
Inline fragments#
Meta: inline fragments are selection syntax, so the full treatment — the field-selecting form, the lazy narrowing form, null/assertion behavior — lives with the rest of selection in GraphQL interop. Keep this as a pointer, not a second copy.
An inline fragment selects a different set of fields for each concrete type. It works on single values and lists:
let picked = pets.{{
... on Cat {{ name, lives }}
... on Dog {{ name, tricks }}
}}
JSON.encode(picked)
- the lazy form (
... on Cat, no field block) narrows without selecting, and... on Cat!asserts - see GraphQL interop for the full rules
Interface vs. union vs. enum#
Meta: newcomers conflate these; a one-line contrast keeps them straight. (enums live in Enums and scalars.)
| what it is | members | discriminate with | open to extension | |
|---|---|---|---|---|
| interface | a shared field contract | object/interface types that implement it | case type patterns, inline fragments |
yes — any type can implement |
| union | a closed set of object types | object types only, listed explicitly | case type patterns, inline fragments |
no — fixed member list |
| enum | a closed set of named constants | bare identifiers (RED) |
case value patterns |
no — fixed value list |