spatie/typescript-transformer

Use arrays with PHP types

Closed this issue · 3 comments

jaulz commented

Right now we have to use something like this (please correct me if I'm wrong) to create array types:

  #[LiteralTypeScriptType('App.Http.Resources.Email[]|null')]
  public ?array $emails;

It would be great if we could reference PHP types directly and generate an array based on it.

You could do something like this:

#[TypeScriptType('?'.Email::class.'[]')]
public ?array $emails;

Which should do the trick, or you could implement your own attribute extending: https://github.com/spatie/typescript-transformer/blob/master/src/Attributes/TypeScriptTransformableAttribute.php this will automatically be converted to TypeScript. You could create an TypeScriptArray attribute?

Closed due inactivity

Hi, i have similar situation: array which can contains more than 10 types, and likely, it works with this construction)

        /** @var array<WaveTextBlockResource|ResultsBlockResource|VideoBlockResource|AwardsBlockResource|ProductExplanationBlockResource|SchoolListBlockResource|ReviewsBlockResource> */

        public readonly ?array $content,

but yeah, because we can't use multiline in PHPDoc it looks awful, so i create custom attribute for this as you said)

        #[TypeScriptArrayOfTypes([
            WaveTextBlockResource::class,
            ResultsBlockResource::class,
            VideoBlockResource::class,
            AwardsBlockResource::class,
            ProductExplanationBlockResource::class,
            SchoolListBlockResource::class,
            ReviewsBlockResource::class,
            DelimiterBlockResource::class,
            FAQsBlockResource::class,
            BenefitsBlockResource::class,
            MediaTextBlockResource::class,
            TrainingListBlockResource::class,
        ])]
        public readonly ?array $content

but still can use phpdoc array for simple situation without any modification)