PHPackages                             spatie/typed - 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. spatie/typed

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

spatie/typed
============

Improvements to PHP's type system in userland: generics, typed lists, tuples and structs

0.1.2(5y ago)32113.2k↓75%152MITPHPPHP ^7.1

Since May 25Pushed 5y ago12 watchersCompare

[ Source](https://github.com/spatie/typed)[ Packagist](https://packagist.org/packages/spatie/typed)[ Docs](https://github.com/spatie/typed)[ RSS](/packages/spatie-typed/feed)WikiDiscussions master Synced 2d ago

READMEChangelog (6)Dependencies (3)Versions (7)Used By (2)

Improved PHP type system in userland
====================================

[](#improved-php-type-system-in-userland)

[![Latest Version on Packagist](https://camo.githubusercontent.com/8ef0c62f71df4003559e4164be8cad02fd1b6474cff8fcd58c09b3586b2063ef/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f7370617469652f74797065642e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/spatie/typed)[![Build Status](https://camo.githubusercontent.com/3b7758f43a4f773affa2a5b7d9968556d3a237849376dc33113d3aa4224d99c1/68747470733a2f2f696d672e736869656c64732e696f2f7472617669732f7370617469652f74797065642f6d61737465722e7376673f7374796c653d666c61742d737175617265)](https://travis-ci.org/spatie/typed)[![StyleCI](https://camo.githubusercontent.com/1c9d706f692c4b9a19a15960bef6787daf67f4abf3783335e90c5bb08a9b58e3/68747470733a2f2f6769746875622e7374796c6563692e696f2f7265706f732f3133343734343230382f736869656c643f6272616e63683d6d6173746572)](https://github.styleci.io/repos/134744208)[![Quality Score](https://camo.githubusercontent.com/1e96408b0f95e32fd493c926dc6bfcba27c8555c4403ee9c3750ca0eff756644/68747470733a2f2f696d672e736869656c64732e696f2f7363727574696e697a65722f672f7370617469652f74797065642e7376673f7374796c653d666c61742d737175617265)](https://scrutinizer-ci.com/g/spatie/typed)[![Total Downloads](https://camo.githubusercontent.com/c6078e191ee9c2658ee54f73137cfd313b708f9181b8f285c97d4b26ade02d9d/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f7370617469652f74797065642e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/spatie/typed)

This package is a mere proof of concept about what's possible in PHP's userland to improve type checking. It adds support for type inference, generics, union types, typed lists, tuples and structs. Because all is done in userland, there are limitations on what syntax is possible.

Support us
----------

[](#support-us)

[![](https://camo.githubusercontent.com/59a6d3cb3693ecb842c38ae35dbd29948dbdbca03bd6defa4c02671241f4cbec/68747470733a2f2f6769746875622d6164732e73332e65752d63656e7472616c2d312e616d617a6f6e6177732e636f6d2f74797065642e6a70673f743d31)](https://spatie.be/github-ad-click/typed)

We invest a lot of resources into creating [best in class open source packages](https://spatie.be/open-source). You can support us by [buying one of our paid products](https://spatie.be/open-source/support-us).

We highly appreciate you sending us a postcard from your hometown, mentioning which of our package(s) you are using. You'll find our address on [our contact page](https://spatie.be/about-us). We publish all received postcards on [our virtual postcard wall](https://spatie.be/open-source/postcards).

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

[](#installation)

You can install the package via composer:

```
composer require spatie/typed
```

Usage
-----

[](#usage)

### Type inference

[](#type-inference)

Both collections, tuples and structs support inferred types. This means that all examples are also possible, without manually specifying types. For example:

```
// This collection will only allow objects of type `Post` in it.
$postCollection = new Collection([new Post()]);

// This tuple will keep its signature of (Point, Point).
$vector = new Tuple(new Point(30, 5), new Point(120, 0));

// This struct's fields are autmoatically type checked.
$struct = [
    'foo' => new Post(),
    'bar' => function () {
        // ...
    },
];
```

The following examples all show the manual type configuration. There are some cases where type inference falls short, and you have to fall back on manually defining them. You might also prefer the manual approach, for clarity's sake.

Note that type may be partially inferred. Some fields in tuples or structs may be type definitions, others may be real values. Uninitialised types will throw an error on read.

### Typed lists and collections:

[](#typed-lists-and-collections)

```
$list = new Collection(T::bool());

$list[] = new Post(); // TypeError
```

It's possible to directly initialise a collection with data after construction.

```
$list = (new Collection(T::string()))->set(['a', 'b', 'c']);
```

This package also provides some predefined lists, as shortcuts.

```
$list = new IntegerList([1, 4]);

$list[] = 'a'; // TypeError
```

### Generics:

[](#generics)

Generic types wrap around classes, allowing you to not creating a custom type for every class.

```
$postList = new Collection(T::generic(Post::class));

$postList[] = 1; // TypeError
```

### Tuples:

[](#tuples)

```
$point = new Tuple(T::float(), T::float());

$point[0] = 1.5;
$point[1] = 3;

$point[0] = 'a'; // TypeError
$point['a'] = 1; // TypeError
$point[10] = 1; // TypeError
```

Like lists, a tuple can also be given some data after construction with the `set` function.

```
$tuple = (new Tuple(T::string(), T::array()))->set('abc', []);
```

### Structs:

[](#structs)

```
$developer = new Struct([
    'name' => T::string(),
    'age' => T::int(),
    'second_name' => T::nullable(T::string()),
]);

$developer['name'] = 'Brent';
$developer['second_name'] = 'John';

$developer->set([
    'name' => 'BrenDt',
    'age' => 23,
    'second_name' => null,
]);

echo $developer->age;

$developer->name = 'Brent';

$developer->age = 'abc' // TypeError
$developer->somethingElse = 'abc' // TypeError
```

### Nullable type

[](#nullable-type)

A nullable type can be defined in two, functionally identical, ways:

```
$list1 = new Collection(T::int()->nullable());

$list2 = new Collection(T::nullable(T::int()));
```

### Union Type

[](#union-type)

A union type means a collection of multiple types.

```
$list = new Collection(T::union(T::int(), T::float()));

$list[] = 1;
$list[] = 1.1;

$list[] = 'abc'; // TypeError
```

Union types may also be nullable and contain generics.

### What's not included:

[](#whats-not-included)

- Proper syntax.
- IDE auto completion for generic types.
- Prevention of type casting between scalar types.
- Type hint generics in functions.

Creating your own types
-----------------------

[](#creating-your-own-types)

The `GenericType` or `T::generic()` can be used to create structures of that type. It is, however, also possible to create your own types without generics. Let's take the example of `Post`. The generic approach works without adding custom types.

```
$postList = new Collection(T::generic(Post::class));

$postList[] = new Post();
$postList[] = 1; // TypeError
```

The `generic` part can be skipped if you create your own type.

```
use Spatie\Typed\Type;
use Spatie\Typed\Types\Nullable;

class PostType implements Type
{
    use Nullable;

    public function validate($post): Post
    {
        return $post;
    }
}
```

Now you can use `PostType` directly:

```
$postList = new Collection(new PostType());
```

You're also free to extend the `T` helper.

```
class T extends Spatie\Typed\T
{
    public static function post(): PostType
    {
        return new PostType();
    }
}

// ...

$postList = new Collection(T::post());
```

The `Nullable` trait adds the following simple snippet, so that the type can be made nullable when used.

```
public function nullable(): NullType
{
    return new NullType($this);
}
```

> **Note:** It's recommended to also implement `__toString` in your own type classes.

Extending data structures
-------------------------

[](#extending-data-structures)

You're free to extend the existing data structures. For example, you could make shorthand tuples like so:

```
class Coordinates extends Tuple
{
    public function __construct(int $x, int $y)
    {
        parent::__construct(T::int(), T::int());

        $this[0] = $x;
        $this[1] = $y;
    }
}
```

Why did we build this?
----------------------

[](#why-did-we-build-this)

PHP has a very weak type system. This is simultaneously a strength and a weakness. Weak type systems offer a very flexible development platform, while strong type systems can prevent certain bugs from happening at runtime.

In its current state, PHP's type system isn't ready for some of the features many want. Take, for example, a look at some RFC's proposing changes to the current type system.

- Generics:
- Typed properties:
- Readonly properties: [https://wiki.php.net/rfc/readonly\_properties](https://wiki.php.net/rfc/readonly_properties)

Some of those are already declined because of runtime performance issues, or implementation difficulties. This package is a thought experiment of what we could do if those features are implemented in PHP, usable with native syntax.

For example, the following syntax would be much more preferable over how this package does it.

```
$postList = new Collection();

// vs.

$postList[] = new Collection(T::generic(Post::class));
```

Anyways, it's stuff to think about. And maybe PHP's type system is fine as it is now? You can read more about type safety [on my blog](https://www.stitcher.io/blog/liskov-and-type-safety).

Contributing
------------

[](#contributing)

Please see [CONTRIBUTING](CONTRIBUTING.md) for details.

Security
--------

[](#security)

If you discover any security related issues, please email  instead of using the issue tracker.

Postcardware
------------

[](#postcardware)

You're free to use this package, but if it makes it to your production environment we highly appreciate you sending us a postcard from your hometown, mentioning which of our package(s) you are using.

Our address is: Spatie, Kruikstraat 22, 2018 Antwerp, Belgium.

We publish all received postcards [on our company website](https://spatie.be/en/opensource/postcards).

Credits
-------

[](#credits)

- [Brent Roose](https://github.com/brendt)
- [All Contributors](../../contributors)

License
-------

[](#license)

The MIT License (MIT). Please see [License File](LICENSE.md) for more information.

###  Health Score

36

—

LowBetter than 82% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity38

Limited adoption so far

Community26

Small or concentrated contributor base

Maturity52

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 60.8% 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 ~181 days

Recently: every ~227 days

Total

6

Last Release

2001d ago

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/7535935?v=4)[Spatie](/maintainers/spatie)[@spatie](https://github.com/spatie)

---

Top Contributors

[![brendt](https://avatars.githubusercontent.com/u/6905297?v=4)](https://github.com/brendt "brendt (76 commits)")[![freekmurze](https://avatars.githubusercontent.com/u/483853?v=4)](https://github.com/freekmurze "freekmurze (22 commits)")[![localheinz](https://avatars.githubusercontent.com/u/605483?v=4)](https://github.com/localheinz "localheinz (12 commits)")[![Furgas](https://avatars.githubusercontent.com/u/715407?v=4)](https://github.com/Furgas "Furgas (5 commits)")[![AdrianMrn](https://avatars.githubusercontent.com/u/12762044?v=4)](https://github.com/AdrianMrn "AdrianMrn (4 commits)")[![peter279k](https://avatars.githubusercontent.com/u/9021747?v=4)](https://github.com/peter279k "peter279k (2 commits)")[![waknauss](https://avatars.githubusercontent.com/u/20912626?v=4)](https://github.com/waknauss "waknauss (2 commits)")[![BackEndTea](https://avatars.githubusercontent.com/u/14289961?v=4)](https://github.com/BackEndTea "BackEndTea (1 commits)")[![akoepcke](https://avatars.githubusercontent.com/u/5311185?v=4)](https://github.com/akoepcke "akoepcke (1 commits)")

---

Tags

genericsstructstuplestypesspatietypedgenericstuplestructstyped list

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/spatie-typed/health.svg)

```
[![Health](https://phpackages.com/badges/spatie-typed/health.svg)](https://phpackages.com/packages/spatie-typed)
```

###  Alternatives

[spatie/laravel-package-tools

Tools for creating Laravel packages

935125.5M7.0k](/packages/spatie-laravel-package-tools)[spatie/laravel-data

Create unified resources and data transfer objects

1.7k28.9M627](/packages/spatie-laravel-data)[spatie/laravel-analytics

A Laravel package to retrieve Google Analytics data.

3.2k5.7M57](/packages/spatie-laravel-analytics)[spatie/macroable

A trait to dynamically add methods to a class

72659.6M64](/packages/spatie-macroable)[spatie/regex

A sane interface for php's built in preg\_\* functions

1.1k17.1M59](/packages/spatie-regex)[spatie/enum

PHP Enums

84429.1M68](/packages/spatie-enum)

PHPackages © 2026

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