Let's take a look at how we can type individual properties of a PHP class.
##Using PHP's built-in typed properties
Since PHP 7.4 it's possible to use typed properties in a class. This package makes these types an A-class citizen.
class Dto
{
public string $string;
public int $integer;
public float $float;
public bool $bool;
public array $array;
}
It is also possible to use nullable types:
class Dto
{
public ?string $string;
}
Or use other types that can be replaced:
class Dto
{
public DateTime $datetime;
}
##Using docblocks
You can also use docblocks to type properties. A more detailed overview of this can be found here. While PHP's built-in typed properties are great, docblocks allow for a bit more flexibility:
class Dto
{
public $string;
public $integer;
public $float;
public $bool;
public $array;
public $arrayThatMightBeAString;
}
It is also possible to use nullable types in docblocks:
class Dto
{
public $string;
}
And add types for your (custom) objects:
class Dto
{
public $dateTime;
}
Note: always use the fully qualified class name (FCCN). At this moment the package cannot determine imported classes used in a docblock:
use App\DataTransferObjects\UserData;
class Dto
{
public $userData;
public $secondUserData;
}
It's also possible to add compound types:
class Dto
{
public $compound;
}
Or these special PHP specific types:
class Dto
{
public $mixed;
public $scalar;
public $void;
}
You can even reference the object's own type:
class Dto
{
public $self;
public $static;
public $void;
}
These will all transform to a Dto
TypeScript type.
##Transforming arrays
Arrays in PHP and TypeScript (JavaScript) are completely different concepts. This poses a couple of problems we'll address. A PHP array is a multi-use storage/memory structure. In TypeScript, a PHP array can be represented both as an Array
and as an Object
with specified keys.
Depending on how your annotations are written the package will output either an Array
or Object
. Let's have a look at some examples that will transform into an Array
type:
class Dto
{
public $array;
public $another_array;
public $you_propably_wont_write_this;
}
Typing objects can be done as such:
class Dto
{
public $object_with_string_keys;
public $object_with_int_keys;
}
##Combining regular types and docblocks
It is possible and recommended combine regular type with docblock annotations for more specific typing. Let's have a look:
class Dto
{
public array $array;
}
The package knows string[]
is a more specific version of the array
type and will internally remove the redundant Array
type. The outputted type definition looks like this:
array: Array<string>