Aliases
The pAlias function allows you to create a new type alias that inherits all the properties and methods of an existing type, while also providing the flexibility to define custom methods specific to the alias. This is particularly useful when you want to create a type that behaves like an existing type but has additional functionality or a more descriptive name.
In some cases it might be useful to define aliases for already existing types.
In the current implementation, aliases do not really have any specific advantage other than making your code more expressive. Currently, aliases can be used everywhere the aliased type is accepted and vice-versa.
Generally speaking you may want to use aliases to define a subset of values that are meant to have a specific meaning
Example: you might need a type that describes the name of a person; every name is a string; but not every string is a name.
To make clear the distinction you define an alias of the string
type to be the Name
type
We define new aliases using the palias
ts function:
const Age = palias( int );
Now we have a new type to specifically represent ages.
To get a term of the aliased type you can use the from
static method of the class you got from calling palias
:
const someAge: Term<typeof Age> = Age.from( pInt(18) );
To enhance the alias with specific custom methods, we can:
const Age = palias(int, "Age", {
inDogYears: pfn([int], int)(age => age.mul(7)),
nextBirthday: pfn([int], int)(age => age.add(1))
});
which can be used as,
const myAge = Age(20);
const dogYears = myAge.inDogYears(); // 140
In a future version aliases will be able to add constraints over the type the are alias of
as an example whe might want to force every Age
to be non-negative, since a negative age doesn't really make sense
When an alias will be constrained plu-ts
will check for the constraints to be met each time a term with an alias is constructed
and will fail the computation if the constraints are not met
What's the plu-ts
type of my alias?
As explained in the types section, aliases and structs have different plu-ts
level types. To access them we need to use the type
static method defined in the Alias class:
const agePlutsType = Age.type;
So if we want to define a function that accepts an Age
as input we would write:
const pisAdult = plam( Age.type, bool )
( age => age.gtEq( 18 ) );
Or the slightly more efficient version, based on partial function application:
const pisAdult = plessThanEqual.$( 18 )