Skip to content

Instantly share code, notes, and snippets.

@aurimasniekis
Created August 4, 2021 09:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aurimasniekis/e10fe097c00a49fc391c7cce06804a43 to your computer and use it in GitHub Desktop.
Save aurimasniekis/e10fe097c00a49fc391c7cce06804a43 to your computer and use it in GitHub Desktop.
Small example of generating Typescript interfaces from PHP classes
<?php
class BaseView extends View
{
}
class AuthorUserView extends BaseView
{
#[Property(type: 'string')]
public Ulid $id;
public string $fullName;
public string $email;
public function __construct(User $user)
{
$this->id = $user->getId();
$this->fullName = $user->getFullName();
$this->email = $user->getEmail();
}
}
class HasCreatedBy extends View
{
/**
* @template U
*
* @var U
*/
#[GenericTypeVariable('U')]
private array $createdBy;
}
class FullClientView extends BaseView
{
use HasIdTrait;
use HasTimestampsTrait;
use HasAuthorTrait;
public string $companyName;
public ?string $email;
}
/**
* @template T
*/
#[GenericTypeVariable('U')]
class PaginatedResultView extends BaseView
{
public int $total;
/**
* @var array<string, T>
*/
#[GenericTypeVariable(extends: HasCreatedBy::class)]
public array $data;
}
#[GenericTypeValue(AuthorUserView::class, 'U')]
class ListClientView extends BaseView
{
#[GenericTypeValue(FullClientView::class, variable: 'T')]
public PaginatedResultView $clients;
public function __construct(PaginatedResult $result)
{
$this->clients = $this->paginated(FullClientView::class, $result);
}
}
export interface BaseView {
}
export interface AuthorUserView extends BaseView {
id: string;
fullName: string;
email: string;
}
export interface HasCreatedBy<U> {
createdBy: U;
}
export interface FullClientView extends BaseView {
companyName: string;
email: string | null;
id: string;
createdAt: number;
updatedAt: number | null;
createdBy: AuthorUserView;
updatedBy: AuthorUserView | null;
}
export interface PaginatedResultView<U, T extends HasCreatedBy<U>> extends BaseView {
total: number;
data: Record<string, T>;
}
export interface ListClientView extends BaseView {
clients: PaginatedResultView<AuthorUserView, FullClientView>;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment