PHPackages                             forrest79/strict-types - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. forrest79/strict-types

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

forrest79/strict-types
======================

Narrowing and documenting PHP types

v1.0.1(2mo ago)019BSD-3-ClausePHPPHP ^8.3CI passing

Since Feb 25Pushed 2mo agoCompare

[ Source](https://github.com/forrest79/strict-types)[ Packagist](https://packagist.org/packages/forrest79/strict-types)[ RSS](/packages/forrest79-strict-types/feed)WikiDiscussions master Synced 1mo ago

READMEChangelogDependencies (7)Versions (3)Used By (0)

StrictTypes
===========

[](#stricttypes)

[![Latest Stable Version](https://camo.githubusercontent.com/46e4dcf222a2208a98c9e979a3f9ebf1cca5494ecf3e0bfc44920f53d3aa002a/68747470733a2f2f706f7365722e707567782e6f72672f666f727265737437392f7374726963742d74797065732f76)](//packagist.org/packages/forrest79/strict-types)[![Monthly Downloads](https://camo.githubusercontent.com/b995494b9d488ead0d643124c2b48d4b33d330b174259e24909589ebbf45b37e/68747470733a2f2f706f7365722e707567782e6f72672f666f727265737437392f7374726963742d74797065732f642f6d6f6e74686c79)](//packagist.org/packages/forrest79/strict-types)[![License](https://camo.githubusercontent.com/c48ed8af73b7736c91c26b92c9abdd44ddcda486668a35e75e53cd08dd960720/68747470733a2f2f706f7365722e707567782e6f72672f666f727265737437392f7374726963742d74797065732f6c6963656e7365)](//packagist.org/packages/forrest79/strict-types)[![Build](https://github.com/forrest79/strict-types/actions/workflows/build.yml/badge.svg?branch=master)](https://github.com/forrest79/strict-types/actions/workflows/build.yml)[![codecov](https://camo.githubusercontent.com/305103d9b7c260332315a625f26cb55b30637380148fdfc95b24ea23bd0d2e02/68747470733a2f2f636f6465636f762e696f2f67682f666f727265737437392f7374726963742d74797065732f67726170682f62616467652e7376673f746f6b656e3d565346435736364a535a)](https://codecov.io/gh/forrest79/strict-types)

Introduction
------------

[](#introduction)

Provides global `as_*` functions that **check** (not cast) variable types and narrow them for [PHPStan](https://phpstan.org/). In development, when PHP assertions are enabled, an `AssertionError` is thrown if the variable does not match the expected type.

These functions are useful anywhere you receive data as `mixed` and need to assert a concrete type — for example, when reading from a database, decoding JSON, or extracting values from arrays. Instead of writing `@var` annotations that are never verified, you let the library both document and validate the type.

```
// Before: annotation is not checked at all
/** @var int $id */
$id = $row['id'];

// After: type is narrowed for PHPStan and verified in development
$id = as_int($row['id']);
```

> **Important:** These functions do **not** cast values. `as_int('42')` will throw an exception in development — the value must already be an `int`.

Installation
------------

[](#installation)

```
composer require forrest79/strict-types

```

For development install also [forrest79/type-validator](https://github.com/forrest79/type-validator):

```
composer require --dev forrest79/type-validator

```

To enable type narrowing in PHPStan, include `extension.neon` in your PHPStan config:

```
includes:
    - vendor/forrest79/strict-types/extension.neon
```

Functions
---------

[](#functions)

### Simple type functions

[](#simple-type-functions)

Function`as_int(mixed $value): int``as_int_nullable(mixed $value): int|null``as_float(mixed $value): float``as_float_nullable(mixed $value): float|null``as_bool(mixed $value): bool``as_bool_nullable(mixed $value):bool|null``as_string(mixed $value): string``as_string_nullable(mixed $value): string|null`All functions return the original value unchanged if it matches the expected type, or throw an `AssertionError` in development (when assertions are enabled) if it does not.

### Complex type function

[](#complex-type-function)

```
as_type(mixed $value, string $type): mixed
```

Checks `$value` against a PHPDoc type string. The runtime check (powered by [forrest79/type-validator](https://packagist.org/packages/forrest79/type-validator)) runs only when assertions are enabled, so `forrest79/type-validator` is only a dev dependency. The PHPStan extension included with this library narrows the type for PHPStan regardless of whether assertions are enabled.

> Because of PHPStan, the type description must be a static string — it cannot be generated dynamically.

Examples
--------

[](#examples)

### Simple types

[](#simple-types)

```
// Reading from a database row (mixed values)
$id    = as_int($row['id']);          // int
$name  = as_string($row['name']);     // string
$score = as_float($row['score']);     // float
$active = as_bool($row['active']);    // bool

// Nullable variants accept null as well
$deletedAt = as_string_nullable($row['deleted_at']); // string|null
$parentId  = as_int_nullable($row['parent_id']);     // int|null
```

### Complex types with `as_type()`

[](#complex-types-with-as_type)

```
// Decoded JSON is mixed — tell PHPStan and verify at runtime
$data = json_decode($json, true);
$data = as_type($data, 'array');

// A nested structure from an external API
$items = as_type($response['items'], 'list');

// class-string narrowing
$className = as_type($config['handler'], 'class-string');

// Union types
$value = as_type($input, 'int|string');
```

> All types supported by [forrest79/type-validator](https://github.com/forrest79/type-validator) are supported, which covers almost all PHPStan PHPDoc types.

### Replacing `@var` annotations

[](#replacing-var-annotations)

```
// Before — the annotation is never enforced
/** @var array $grouped */
$grouped = buildGroups($data);

// After — verified in development, narrowed for PHPStan
$grouped = as_type(buildGroups($data), 'array');
```

### Passing narrowed values directly to typed parameters

[](#passing-narrowed-values-directly-to-typed-parameters)

```
function processUser(int $id, string $name): void { /* ... */ }

// PHPStan knows the return types, so no extra annotation needed
processUser(
    as_int($payload['id']),
    as_string($payload['name']),
);
```

###  Health Score

40

—

FairBetter than 88% of packages

Maintenance85

Actively maintained with recent releases

Popularity8

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity50

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~4 days

Total

2

Last Release

77d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/d979cd353c6593b44b50f90ff5a5eb4be224f501a70f7cce89d0735867e488e5?d=identicon)[forrest79](/maintainers/forrest79)

---

Top Contributors

[![forrest79](https://avatars.githubusercontent.com/u/160766?v=4)](https://github.com/forrest79 "forrest79 (7 commits)")

---

Tags

phpPHPStanarraylisttypesnarrow

###  Code Quality

Static AnalysisPHPStan

Type Coverage Yes

### Embed Badge

![Health badge](/badges/forrest79-strict-types/health.svg)

```
[![Health](https://phpackages.com/badges/forrest79-strict-types/health.svg)](https://phpackages.com/packages/forrest79-strict-types)
```

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
