Skip to content

Union types

A|B accepts a value of type A or of type B. A type can also list exact values, such as "read"|"write". The page Nullable types shows both, with examples.

Use a type alias when a type is long or used in many places. Use mixed when the type is not known.

A member every class of a union declares

A variable of a union of classes, such as Box|Circle, is an object of one of those classes. You can read a property or call a method of it when every class has that member with the same type. A method needs the same parameters and return type. The member must also be visible where you use it.

Use ?-> on a union that may be null, such as ?Box|Circle. A write compiles when no class makes the property readonly and every class has the same set visibility. isinit does not compile on a property of a union.

If one class does not have the member, the program does not compile. The same is true when the types differ, or when the member is not visible in one class. The error is E0881, and its message names the class. An interface is not allowed in such a union.

The examples below read a property of two shipping classes and call a method of two payment classes. The last one is a compile error.

A property both classes declare

<?nvs
// Shows how to read a property that every class of a union declares.
final class Courier
{
public string $label = 'Courier, next day';
public function constructor(public int $weight)
{ }
}
final class Pickup
{
public string $label = 'Pickup at the shop';
public function constructor(public int $weight)
{ }
}
final class Order
{
// Small parcels go by courier. Heavy parcels are picked up at the shop.
public static function shipping(int $weight): Courier|Pickup
{
if ($weight > 20) {
return new Pickup($weight);
}
return new Courier($weight);
}
}
// Both classes declare `string $label` and `int $weight`.
// So `$ship->label` compiles without a test of the class.
array<int> $weights = [3, 25];
foreach ($weights as int $weight) {
Courier|Pickup $ship = Order::shipping($weight);
echo $ship->weight, ' kg: ', $ship->label, "\n";
}
// `?->` reads a property of a union that may be `null`.
// Here the variable is `null`, so `??` prints `not chosen`.
?Courier|Pickup $later = null;
echo $later?->label ?? 'not chosen', "\n";
// A write works too, because `$label` has the same type in both classes.
Courier|Pickup $gift = new Courier(1);
$gift->label = 'Courier, gift wrapped';
echo $gift->label, "\n";
Output
3 kg: Courier, next day
25 kg: Pickup at the shop
not chosen
Courier, gift wrapped

A method both classes declare

<?nvs
// Shows how to call a method that every class of a union declares.
final class Card
{
public function constructor(public string $last4)
{ }
public function fee(int $cents): int
{
return $cents >= 5000 ? 0 : 30;
}
public function describe(): string
{
return 'card ending ' . $this->last4;
}
}
final class Transfer
{
public function constructor(public string $bank)
{ }
public function fee(int $cents): int
{
return $cents >= 100000 ? 0 : 50;
}
public function describe(): string
{
return 'transfer from ' . $this->bank;
}
}
// Each call runs `fee` and `describe` of the class the value is.
// For 10000 cents, the card fee is `0` and the transfer fee is `50`.
array<Card|Transfer> $payments = [new Card('4242'), new Transfer('City Bank')];
foreach ($payments as Card|Transfer $payment) {
echo $payment->describe(), ': fee ', $payment->fee(10000), " cents\n";
}
Output
card ending 4242: fee 0 cents
transfer from City Bank: fee 50 cents

A member one class lacks

<?nvs
// Shows that a property must exist in every class of the union.
// `Pickup` has no `$tracking`, so this program does not compile.
// proof: compile-error
final class Courier
{
public string $tracking = 'TR-1001';
public function constructor()
{ }
}
final class Pickup
{
public string $shop = 'Main Street';
public function constructor()
{ }
}
Courier|Pickup $ship = new Pickup();
echo $ship->tracking, "\n";
Output
error[E0881]: `Pickup` has no property `$tracking`
--> 03-a-member-one-class-lacks.nvs:21:6
|
21 | echo $ship->tracking, "\n";
| ^^^^^^^^^^^^^^^ used through `Courier|Pickup` here
= help: you can use a member through a union only when every class has it with the same type, and it is visible here. Otherwise, test the value with `is` first
error: aborting due to 1 error
To read what a code means and how to fix it, run `nvs agent show <code>`.

Type aliases

A type alias gives a type a short name. After type UserId = uint;, UserId and uint are the same type. A value of one is a value of the other, so you never convert between them.

You write an alias at the top level of a file, or inside a class, interface or enum. An alias inside a class belongs to that class. Outside the class, you write the class name first: Basket::Lines.

An alias cannot be a second name for one class, because a class already has a name. Use an alias for a type that is long to write: a union, a nested array, or the fields of an object a method returns.

An alias exists only while the program compiles. It has no cost while the program runs.

Example 04 names a nullable class and a union. Example 05 shows that an alias of one class does not compile.

A short name for a long type

<?nvs
// Three aliases at the top of the file give three types a short name.
// An alias and its type are the same type, so a value moves between them without `as`.
type UserId = uint;
type Answer = int|string;
type Grid = array<array<float>>;
class Report
{
public static function line(UserId $id, Answer $answer): string
{
return 'user ' . ($id as string) . ' answered ' . ($answer as string);
}
}
UserId $id = 1042;
uint $plain = $id; // the alias and `uint` are one type, in both directions
echo Report::line($id, 7), "\n";
echo Report::line($plain, 'maybe'), "\n";
Grid $grid = [[1.5, 2.0], [0.5]];
echo $grid[0][1], ' ', $grid[1][0], "\n";
Output
user 1042 answered 7
user 1042 answered maybe
2 0.5

A name that belongs to a class

<?nvs
// You can declare a type alias inside a class. Inside that class, you write
// the short name `Lines`. Outside it, you write `Basket::Lines`.
// A subclass does not inherit the alias.
final class Basket
{
type Lines = array<string>;
public function constructor(public Lines $lines)
{}
public function add(string $line): Lines
{
$this->lines[] = $line;
return $this->lines; // inside the class: the short name
}
}
class Printer
{
public static function show(Basket::Lines $lines): void
{ // outside the class: the class name first
foreach ($lines as string $line) {
echo '- ', $line, "\n";
}
}
}
Basket $basket = new Basket(['two coffees']);
Printer::show($basket->add('one tea'));
Output
- two coffees
- one tea

The shape a method hands back

<?nvs
// `type Invoice` gives a name to the fields that these methods return.
// Each method uses the name `Invoice`, so the fields are written only once.
// To add a field, you change only this one line.
type Invoice = { number: string, total: decimal, paid: bool };
class Billing
{
public static function build(string $number, decimal $total): Invoice
{
return { number: $number, total: $total, paid: false };
}
public static function settle(Invoice $invoice): Invoice
{
return { number: $invoice->number, total: $invoice->total, paid: true };
}
public static function line(Invoice $invoice): string
{
return $invoice->number
. ' '
. ($invoice->total as string)
. ($invoice->paid ? ' (paid)' : ' (open)');
}
}
Invoice $draft = Billing::build('INV-1042', 19.99 as decimal);
echo Billing::line($draft), "\n";
echo Billing::line(Billing::settle($draft)), "\n";
Output
INV-1042 19.99 (open)
INV-1042 19.99 (paid)

A nullable class and a union

<?nvs
// `MaybeUser` is a `User` or `null`. `Id` is an `int` or a `string`.
class User
{
public int $n = 7;
}
type Id = int|string;
type MaybeUser = ?User;
Id $a = 1;
Id $b = 'x';
MaybeUser $u = new User();
echo $a, $b, ' ', $u?->n, "\n";
Output
1x 7

An alias of one class

<?nvs
// Shows that an alias cannot name one class on its own. `Foo` already has a name.
// This program does not compile.
// proof: compile-error
class Foo
{
public int $n = 1;
}
type Bar = Foo;
Output
error[E0307]: a `type` alias may not name a single class, interface or enum on its own
--> 05-an-alias-of-one-class.nvs:11:12
|
11 | type Bar = Foo;
| ^^^ aliases exactly one class-shaped atom
= help: a class already has its own name, so write the class name. An alias can name a union, an intersection or an `array<...>`
error: aborting due to 1 error
To read what a code means and how to fix it, run `nvs agent show <code>`.

Details

An alias name is written in PascalCase. type user_id = uint; is the error E0110.

An alias at the top level of a file can be used anywhere in that file, also above its declaration. An alias inside a method body or a block, such as an if, is the error E0233.

An alias inside a class, interface or enum has no visibility. public type Lines = …; is the error E0133. Inside its class you write the short name. Everywhere else you write Owner::Name.

A child class does not inherit an alias. Lines in a child class of Basket is the error E0303. Write Basket::Lines there.

An alias of a single class, interface or enum is the error E0307. ?Foo, a union, an object shape and array<Foo> are allowed.

An alias may use another alias, such as type Ids = array<Id>;. An alias that contains itself is the error E0310, such as type Tree = array<Tree>;. Use a class for a type that contains itself.

Two declarations with the same name are the error E0304. This is also true for an alias and a class with the same name.

mixed

mixed is the one type Novis does not check. A mixed variable can contain a value of any type.

Input from outside the program has the type mixed: a query string, a form post, decoded JSON. Convert each value to the type you need with as. If that is not possible, as throws an error. is tests what the value is and does not convert it.

A mixed value is never converted to a narrower type for you. Passing one to a string parameter does not compile until you write as string.

Good to know: an operation on a mixed value is slower than on a declared type. Convert the value once, close to where it arrives.

The examples below read a page number from a query string, describe each field of a decoded payload, and convert an order line. The last two use a mixed value directly and show the compile error.

Read a page number out of a query string

<?nvs
// Query parameters have the type `mixed`, because nothing has checked them yet.
// `as ?uint` converts a value to a whole number. If that is not possible,
// the result is `null`, and `??` gives the default value instead.
array<mixed> $query = ['page' => '3', 'size' => 'abc', 'sort' => 'name'];
uint $firstPage = 1;
uint $defaultSize = 20;
uint $page = ($query['page'] as ?uint) ?? $firstPage;
uint $size = ($query['size'] as ?uint) ?? $defaultSize;
echo 'page ', $page, ', ', $size, " per page\n";
Output
page 3, 20 per page

Say what each field of a decoded payload is

<?nvs
// Describes each field of a decoded JSON document. Each field is a `mixed` value.
// `is` tests the type of a value and does not convert it.
array<mixed> $payload = ['id' => 4102, 'name' => 'Ada', 'paid' => true, 'note' => null];
foreach ($payload as tainted string $field => mixed $value) {
if ($value is int) {
echo $field, " is a whole number\n";
} elseif ($value is string) {
echo $field, " is text\n";
} elseif ($value is bool) {
echo $field, " is a yes or no\n";
} else {
echo $field, " was not sent\n";
}
}
Output
id is a whole number
name is text
paid is a yes or no
note was not sent

Turn one untrusted order line into typed values

<?nvs
// A handler converts each value once, at the start, and then works with typed values.
// If a value does not convert, `as` throws an error. The program reports the line and skips it.
// Only a line whose three values all converted is added to the total.
array<mixed> $lines = [
['sku' => 'A-1', 'quantity' => '2', 'price' => '9.95'],
['sku' => 'B-7', 'quantity' => 'many', 'price' => '4.00'],
['sku' => 'C-3', 'quantity' => 1, 'price' => '12.50'],
];
decimal $total = 0.00;
foreach ($lines as mixed $line) {
try {
tainted string $sku = $line['sku'] as string;
uint $quantity = $line['quantity'] as uint;
decimal $price = $line['price'] as decimal;
$total = $total + $price * $quantity;
echo $sku, ': ', $quantity, ' x ', $price, "\n";
} catch (Throwable $e) {
echo "skipped a line that did not convert\n";
}
}
echo 'total ', $total, "\n";
Output
A-1: 2 x 9.95
skipped a line that did not convert
C-3: 1 x 12.50
total 32.40

Use a mixed value directly

<?nvs
// Shows the operations you can use on a `mixed` value without converting it first.
mixed $m = 5;
mixed $row = ['k' => 'v'];
mixed $text = 'x';
// Each operation checks the value while the program runs. This prints `6 5 v xy X`.
echo $m + 1, ' ', $m as string, ' ', $row['k'], ' ', $text . 'y', ' ', Core\Str::upper($text as string), "\n";
// Arithmetic needs a number, so `"abc" + 1` throws an error.
mixed $bad = 'abc';
try {
echo $bad + 1, "\n";
} catch (RuntimeError $e) {
echo "no arithmetic on text\n";
}
Output
6 5 v xy X
no arithmetic on text

Convert before a typed parameter

<?nvs
// Shows that a `mixed` value is not passed to a `string` parameter without `as string`.
// This program does not compile.
// proof: compile-error
mixed $text = 'x';
echo Core\Str::upper($text), "\n";
Output
error[E0401]: expected `string`, found `mixed`
--> 05-convert-before-a-typed-parameter.nvs:7:22
|
7 | echo Core\Str::upper($text), "\n";
| ^^^^^ this is `mixed`
error: aborting due to 1 error
To read what a code means and how to fix it, run `nvs agent show <code>`.

Details

You can use a mixed value in arithmetic, as a condition, with [], with ->, with . and with is or as. Each operation checks the value while the program runs. If the value has the wrong type, it throws an error.

Arithmetic needs a number. "abc" + 1 throws a RuntimeError, and so does "5" + 1. Convert text first: ($m as int) + 1. An int and a float add as they do without mixed: 5 + 1.5 is 6.5.

== never converts a value. A mixed "5" is not equal to 5.

. joins a number or a string. An array with . throws a RuntimeError. [] on a value that is not an array throws a RuntimeError, and so does -> for a field the object does not have. Calling a method on a value that is not an object throws a LogicError.

A mixed value is never assigned to a narrower type without as. int $i = $m; is the error E0401, and so is a mixed argument for a string parameter.

  • Do use a list of exact values for a small set of strings, such as "asc"|"desc".
  • Do use an enum when the set has a name and is used in many places.
  • Don’t use mixed for a value whose type you know. You lose the compiler’s checks.