spatie/typescript-transformer

How to deal with model properties?

Closed this issue · 2 comments

jaulz commented

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

Hi @jaulz,

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

jaulz commented

@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! 😊