spatie / typescript-transformer

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

How to deal with model properties? #9

Closed jaulz closed 3 years ago

jaulz commented 3 years ago

Thanks for this great library as it worked pretty well so far for me. Though, now I face an issue when I define properties on my models:

  public int $id;
  public string $name;

which is correctly transformed to:

export type Team = {
    id: number;
    name: string;
    ...
}

However, PHP complains now:

Typed property App\Models\Team::$id must not be accessed before initialization

Any idea how I can avoid this error? I also tried to use default values for the properties but then again my models lose the actual database values.

If I define them like this I can avoid the PHP error but then the Typescript type is also nullable:

private ?string $name = NULL;

P.S.: I use PHP 8.0

rubenvanassche commented 3 years ago

Hi @jaulz,

Could provide me the full backtrace of the exception, not sure where this is happening.

jaulz commented 3 years ago

@rubenvanassche the exception was triggered by PHP itself I think. Though, eventually I just made it like in the examples in the docs and used separate classes that extend DataTransferObject. Thanks anyway! 😊