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 callable values. Accepts closures, function names, array callables, and invokable objects.

Documentation

Code

<?php

declare(strict_types=1);

use function Flow\Types\DSL\type_callable;

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

$callback = fn (int $x) => $x * 2;
$result = type_callable()->assert($callback);

echo 'Assert closure: ' . (is_callable($result) ? 'callable' : 'not callable') . "\n";
echo 'Call result: ' . $result(5) . "\n";
echo 'Assert built-in: ' . (is_callable(type_callable()->assert('strtoupper')) ? 'callable' : 'not callable') . "\n";
Contributors

Built in the open.

Join us on GitHub
scroll back to top