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!
}

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))]
=> ["hello, Ada", "hello, unit-7"]

Conformance is checked. A missing field, or one whose type doesn't fit, is an error:

type Rock implements Named { weight: Int! }
Type error: object Rock is missing `name(): String!`, required by interface Named
type Pebble implements Named { name: Int! }
Type error: field "name": type Int! is not compatible with interface type String!

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" }
Type error: field "name" of Secret is private (`let`), but interface Named makes it public

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)
Type error: argument "n": cannot use Named! as Named!: Named here is the type itself, not a value of that type

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))
=> "hello, Grace"

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))
Type error: argument "n": cannot use Pebble! as Named!: - missing field "name"

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(_) }
=> ["hello, Ada", "hello, Turing"]

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! }
Type error: interface Label is missing `name(): String!`, required by interface Named

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 }
=> ["Ada"]

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 }
Type error: field "headline": type String is not compatible with interface type 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") + "|"
=> " hi|"

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! }
Type error: field "key": type ID! is not compatible with interface type String!

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)
=> "bee"

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 }
}
Type error: field "best", argument "x": the implementation bounds a by Numeric, but the interface's callers may pass any Ordered type for a!

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 }
}
Type error: field "best", argument "x": type String! doesn't fit interface type a! for every type the interface's callers pick

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))]
=> ["Ada, age 36", "Acme, 12 people", "unit-7"]

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 }
Type error: pattern Company! can't match a value of type Person!

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"
}
→ query Query {favoriteNode{id __typename}} → query Query {node(id:"Post:2"){... on Post{title}}} → query Query {node(id:"Post:2"){... on Post{author{name}}}}
=> "Second Post by Jane Smith"

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
Type error: union member Mood must be an object type, got enum
union Aquarium = Cat | Fish
Type error: union member Fish not found

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 ")}`
  }
}
=> ["Tom has 9 lives", "Rex knows sit and stay"]

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 }
}
Type error: return type mismatch: declared String!, inferred String

A type that no member is can't be matched:

case (pets[0]!) { p: Person! => p.name }
Type error: type Person is not a member of union Pet

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)
=> "[{\"name\":\"Tom\",\"lives\":9},{\"name\":\"Rex\",\"tricks\":[\"sit\",\"stay\"]}]"

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