# man > Moose::Util::TypeConstraints

---
type: CommandReference
command: Moose::Util::TypeConstraints
mode: man
section: 3pm
source: man-pages
---

## Quick Reference

- `subtype 'Name', as 'Parent', where { ... }, message { ... };` — create named subtype
- `coerce 'Name', from 'OtherName', via { ... };` — define coercion from one type to another
- `class_type 'ClassName';` — create a subtype of `Object` for a class
- `role_type 'RoleName';` — create a type constraint for a role
- `enum 'Name', [qw(values)];` — create an enum subtype of `Str`
- `union 'Name', [qw(Types)];` — create a union type that matches any of the given types
- `duck_type 'Name', [qw(methods)];` — create a duck typing constraint (subtype of `Object`)
- `maybe_type 'Type';` — create a type that allows `undef` or the given type

## Name

**Moose::Util::TypeConstraints** — Type constraint system for Moose

## Synopsis

perl
use Moose::Util::TypeConstraints;

subtype 'Natural',
    as 'Int',
    where { $_ > 0 };

subtype 'NaturalLessThanTen',
    as 'Natural',
    where { $_ < 10 },
    message { "This number ($_) is not less than ten!" };

coerce 'Num',
    from 'Str',
    via { 0+$_ };

class_type 'DateTimeClass', { class => 'DateTime' };

role_type 'Barks', { role => 'Some::Library::Role::Barks' };

enum 'RGBColors', [qw(red green blue)];

union 'StringOrArray', [qw( String ArrayRef )];

no Moose::Util::TypeConstraints;
## Options

### Type Constraint Constructors

- `subtype 'Name', as 'Parent', where { ... }, message { ... }, inline_as { ... };` — Create a named subtype. If `Parent` is not recognized, a class type constraint is created automatically. Can also be called with a hashref: `subtype('Foo', { where => ..., message => ... })`. Anonymous subtype: `subtype as 'Parent', where { ... }` or `subtype({ where => ..., message => ... })`.
- `type 'Name', where { ... }, message { ... }, inline_as { ... };` — Create a base type with no parent. Can also be called with a hashref: `type('Foo', { where => ..., message => ... })`.
- `class_type($class, ?$options)` — Create a subtype of `Object` named `$class`. Option: `{ class => 'ActualClass' }` to use a different class name.
- `role_type($role, ?$options)` — Create a `Role` type constraint named `$role`. Option: `{ role => 'ActualRole' }` to use a different role name.
- `maybe_type($type)` — Create a type constraint that accepts `undef` or a value of `$type`.
- `duck_type($name, \@methods)` — Create a subtype of `Object` that checks if the value `can()` all methods in `@methods`. Anonymous: `duck_type(\@methods)`.
- `enum($name, \@values)` — Create a subtype of `Str` that matches one of the given strings (case sensitive). Anonymous: `enum(\@values)`.
- `union($name, \@constraints)` — Create a type where any of the constraints may match. Anonymous: `union(\@constraints)`. Supports anonymous child constraints.

#### Sugar Helpers

- `as 'Parent'` — Specify the parent type in a subtype or type definition.
- `where { ... }` — Validation subroutine. Receives value in `$_`, returns true/false.
- `message { ... }` — Custom error message subroutine. Receives invalid value in `$_`, returns a string.
- `inline_as { ... }` — Define an inlinable version of the constraint. Called as a method on `Moose::Meta::TypeConstraint`, receives a variable name string, returns a code string.

### Type Coercion Constructors

- `coerce 'Name', from 'OtherName', via { ... }, from 'ThirdName', via { ... };` — Define one or more coercions to type `Name`. Each `from/via` pair specifies a source type and a transformation subroutine.
- `from 'OtherName'` — Specify the source type for a coercion.
- `via { ... }` — Transformation subroutine. Receives value in `$_`, returns the coerced value.

### Type Constraint Utilities

- `match_on_type $value => ( $type => \&action, ... , ?\&default )` — Dispatch on the type of `$value`. The first matching type executes its action. A catch-all can be provided as the last argument.

### Creating and Finding Type Constraints

- `find_type_constraint($type_name)` — Return the `Moose::Meta::TypeConstraint` object for a named type. Importable.
- `register_type_constraint($type_object)` — Register a type constraint in the global registry. Importable.
- `normalize_type_constraint_name($name)` — Remove whitespace from a type name.
- `create_type_constraint_union($pipe_separated_types | @names)` — Create a union type object.
- `create_named_type_constraint_union($name, $pipe_separated_types | @names)` — Create a named union type object.
- `create_parameterized_type_constraint($type_name)` — Create a parameterized type (e.g., `ArrayRef[Int]`). BaseType must be parameterizable.
- `create_class_type_constraint($class, $options)` — Create a `Moose::Meta::TypeConstraint::Class` object.
- `create_role_type_constraint($role, $options)` — Create a `Moose::Meta::TypeConstraint::Role` object.
- `create_enum_type_constraint($name, $values)` — Create a `Moose::Meta::TypeConstraint::Enum` object.
- `create_duck_type_constraint($name, $methods)` — Create a `Moose::Meta::TypeConstraint::DuckType` object.
- `find_or_parse_type_constraint($type_name)` — Find or parse a union/parameterized type. Returns false if not found.
- `find_or_create_isa_type_constraint($type_name)` — Find or create a class type constraint.
- `find_or_create_does_type_constraint($type_name)` — Find or create a role type constraint.
- `get_type_constraint_registry` — Return the `Moose::Meta::TypeConstraint::Registry` object.
- `list_all_type_constraints` — List all registered type constraint names.
- `list_all_builtin_type_constraints` — List built-in type constraints.
- `export_type_constraints_as_functions` — Export all current type constraints as functions into the caller's namespace.
- `get_all_parameterizable_types` — Return list of all parameterizable type objects.
- `add_parameterizable_type($type)` — Add a type to the list of parameterizable types.

## Default Type Constraints

text
Any
    Item
        Bool
        Maybe[`a]
        Undef
        Defined
            Value
                Str
                    Num
                        Int
                    ClassName
                    RoleName
            Ref
                ScalarRef[`a]
                ArrayRef[`a]
                HashRef[`a]
                CodeRef
                RegexpRef
                GlobRef
                FileHandle
                Object
Types followed by `[`a]` are parameterizable (e.g., `ArrayRef[Int]`). Unknown names in brackets are treated as class names. `Undef` works but may have edge cases. `ClassName` requires the class to be loaded. `RoleName` checks a string is a package that is a role.

## Examples

### Subtype with custom message

perl
subtype 'PositiveInt',
    as 'Int',
    where { $_ > 0 },
    message { "$_ is not a positive integer!" };
### Using duck_type anonymously

perl
has 'cache' => (
    is  => 'ro',
    isa => duck_type( [qw( get_set )] ),
);
### Using enum anonymously

perl
has 'sort_order' => (
    is  => 'ro',
    isa => enum([qw[ ascending descending ]]),
);
### Using union with anonymous types

perl
has 'color' => (
    isa => 'ro',
    isa => union([ 'Int', enum([qw[ red green blue ]]) ]),
);
### Type dispatch with match_on_type

perl
sub ppprint {
    my $x = shift;
    match_on_type $x => (
        HashRef => sub {
            my $hash = shift;
            '{ ' . (join ", " => map { $_ . ' => ' . ppprint( $hash->{$_} ) } sort keys %$hash) . ' }';
        },
        ArrayRef => sub {
            my $array = shift;
            '[ ' . (join ", " => map { ppprint($_) } @$array) . ' ]';
        },
        CodeRef   => sub {'sub { ... }'},
        RegexpRef => sub { 'qr/' . $_ . '/' },
        GlobRef   => sub { '*' . B::svref_2object($_)->NAME },
        Object    => sub { $_->can('to_string') ? $_->to_string : $_ },
        ScalarRef => sub { '\\' . ppprint( ${$_} ) },
        Num       => sub {$_},
        Str       => sub { '"' . $_ . '"' },
        Undef     => sub {'undef'},
        => sub { die "I don't know what $_ is" }
    );
}
### Integration with other constraint modules

perl
type 'HashOfArrayOfObjects',
    where {
        IsHashRef(
            -keys   => HasLength,
            -values => IsArrayRef(IsObject)
        )->(@_);
    };
## See Also

- [Moose](https://metacpan.org/pod/Moose)
- [Moose::Meta::TypeConstraint](https://metacpan.org/pod/Moose::Meta::TypeConstraint)
- [Moose::Meta::TypeConstraint::Class](https://metacpan.org/pod/Moose::Meta::TypeConstraint::Class)
- [Moose::Meta::TypeConstraint::Role](https://metacpan.org/pod/Moose::Meta::TypeConstraint::Role)
- [Moose::Meta::TypeConstraint::Enum](https://metacpan.org/pod/Moose::Meta::TypeConstraint::Enum)
- [Moose::Meta::TypeConstraint::Union](https://metacpan.org/pod/Moose::Meta::TypeConstraint::Union)
- [Moose::Meta::TypeConstraint::DuckType](https://metacpan.org/pod/Moose::Meta::TypeConstraint::DuckType)
- [Moose::Meta::TypeConstraint::Registry](https://metacpan.org/pod/Moose::Meta::TypeConstraint::Registry)
- [Declare::Constraints::Simple](https://metacpan.org/pod/Declare::Constraints::Simple)
- [Test::Deep](https://metacpan.org/pod/Test::Deep)