spatie / typescript-transformer

Transform PHP types to TypeScript
https://docs.spatie.be/typescript-transformer/v2/introduction/
MIT License
275 stars 35 forks source link

There should be a "Transformer order matters!" warning in the docs #33

Closed allejo closed 2 years ago

allejo commented 2 years ago

I really hope I'm not blind here and I missed that warning but I feel like it'd be useful to specify somewhere in the docs that the order in which you specify which Transformers to use matters.

DtoTransformer before EnumTransformer

$config = TypeScriptTransformerConfig::create()
    ->autoDiscoverTypes(__DIR__ . '/../Contracts')
    ->transformToNativeEnums()
    ->transformers([
        DtoTransformer::class,
        EnumTransformer::class,
    ])
    ->outputFile(__DIR__ . '/../../assets/generated/types.d.ts')
;

The above PHP configuration results in DtoTransformer handling everything, including enums which then results in the wrong TypeScript being generated.

declare namespace App.Contracts {
    export type MapDefinition = {
        layers: { [key: string]: any };
        projection: [string, string];
        centerCoordinates: [number, number];
    };
    export type NodeType = {
        name: string;
        value: number;
    };
}

EnumTransformer before DtoTransformer

$config = TypeScriptTransformerConfig::create()
    ->autoDiscoverTypes(__DIR__ . '/../Contracts')
    ->transformToNativeEnums()
    ->transformers([
        EnumTransformer::class,
        DtoTransformer::class,
    ])
    ->outputFile(__DIR__ . '/../../assets/generated/types.d.ts')
;

The above configuration correctly lets the EnumTransformer act first and generate a correct TypeScript enum.

declare namespace App.Contracts {
    export enum NodeType { 'OutdoorPath' = 0, 'Hallway' = 1, 'Room' = 2, 'Stairs' = 3, 'Elevator' = 4 };
    export type MapDefinition = {
        layers: { [key: string]: any };
        projection: [string, string];
        centerCoordinates: [number, number];
    };
}

My ask

In retrospect, it makes complete sense that the order of transformers matters but it wasn't until I ran into this problem that I figured that out. I don't think the behavior should change but the docs should have a warning talking about that fact. I'd send a PR but I'm not sure where to best place that information.

But thank you for this library! It's been such a timesaver for my project! :heart:

rubenvanassche commented 2 years ago

Feel free sending in an PR updating the docs. This page seems the correct place to me: https://spatie.be/docs/typescript-transformer/v2/usage/using-transformers