SR
Click to open github profile
Events

Custom Typescript Types

Learn how you can add your own TypeScript types.


You can use the EVENT_REGISTER_TYPE_DEFINITIONS event to define custom TypeScript type definitions for specific Craft CMS field types.

Initialize Event Listener

Add the following code to your module or plugin to register your custom type definitions:

Queryapiextension.php
use modules\queryapiextension\transformers\NavigationTransformer;

use samuelreichoer\queryapi\events\RegisterTypeDefinitionEvent;
use samuelreichoer\queryapi\models\RegisterTypeDefinition;
use samuelreichoer\queryapi\services\TypescriptService;

Event::on(
    TypescriptService::class,
    TypescriptService::EVENT_REGISTER_TYPE_DEFINITIONS,
    function (RegisterTypeDefinitionEvent $event) {
        $event->typeDefinitions[] = new RegisterTypeDefinition([
            'fieldTypeClass' => 'verbb\hyper\fields\HyperField',
            'staticHardType' => 'export type hello = string',
            'dynamicHardType' => HyperTypeService::class,
            'staticTypeDefinition' => 'hello[]',
            'dynamicDefinitionClass' => HyperTypeService::class,
        ]);
    }
);

Each RegisterTypeDefinition allows the user to define:

  • fieldTypeClass: The Craft field class this applies to (e.g., HyperField::class).
  • staticHardType: A custom hardcoded TypeScript type that will be injected globally (e.g., utility or shared types). It gets overwritten if dynamicHardType is defined.
  • dynamicHardType: A PHP class that can dynamically generate hardcoded types (must implement a method like setHardTypes()).
  • staticTypeDefinition: A fixed return type for this field (e.g., hello[]). It gets overwritten if dynamicHardType is defined.
  • dynamicDefinitionClass: A PHP class that will receive the field and return a context-aware type (must have a method like setTypeByField()).

Creating a Transformer

To set dynamic types you can create a file like the following:

HyperTypeService.php
<?php

namespace modules\queryapiextension\services;

use samuelreichoer\queryapi\services\TypescriptService;
use verbb\hyper\fields\HyperField;

class HyperTypeService extends TypescriptService
{
    // Set type for all fields that have the HyperField class
    public function setTypeByField(HyperField $field): string
    {
        return 'HyperField';
    }

    // Set global type, you can use this in the setTypeByField method.
    public function setCustomHardTypes(): string
    {
        return 'export type HyperField = object';
    }
}

Copyright © 2025 Samuel Reichör