Skip to content
Search
Examples

Types

Description

Type assertions validate values at runtime and throw InvalidArgumentException if the value doesn't match the expected type.
The assert() method returns the validated value with proper type narrowing, enabling static analysis tools like
PHPStan to understand the resulting type. This provides IDE autocompletion and catches type errors during analysis.

<?php

$value = takeFromUser(); // $value is type mixed here

$stringValue = type_string()->assert($value); 

// $valueString is type string here, it's called types narrowing 

Read more about types narrowing


Assert typed maps with specific key and value types. Ensure dictionary-like structures have consistent types throughout.

Documentation

Code

<?php

declare(strict_types=1);

use function Flow\Types\DSL\{type_integer, type_map, type_string};

require __DIR__ . '/vendor/autoload.php';

echo 'Scores: ' . json_encode(type_map(type_string(), type_integer())->assert(['alice' => 100, 'bob' => 85])) . "\n";
Contributors

Built in the open.

Join us on GitHub
scroll back to top