Skip to content

Commit

Permalink
use globalThis for reserved class names
Browse files Browse the repository at this point in the history
  • Loading branch information
chriskapp committed May 24, 2024
1 parent f479eec commit 7e571db
Showing 1 changed file with 20 additions and 1 deletion.
21 changes: 20 additions & 1 deletion src/Generator/TypeScript.php
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,9 @@ protected function writeStruct(Code\Name $name, array $properties, ?string $exte

$code.= ' {' . "\n";

$reservedClassNames = ['Array', 'Record'];
$isReservedClassName = in_array($name->getClass(), $reservedClassNames);

foreach ($properties as $property) {
/** @var Code\Property $property */
// we must use the raw property name since in typescript we dont have a JsonGetter annotation like in Java
Expand All @@ -79,7 +82,12 @@ protected function writeStruct(Code\Name $name, array $properties, ?string $exte
$propertyName = '"' . $propertyName . '"';
}

$code.= $this->indent . $propertyName . ($property->isRequired() ? '' : '?') . ': ' . $property->getType() . "\n";
$type = $property->getType();
if ($isReservedClassName) {
$type = $this->appendGlobalThis($type, $reservedClassNames);
}

$code.= $this->indent . $propertyName . ($property->isRequired() ? '' : '?') . ': ' . $type . "\n";
}

$code.= '}' . "\n";
Expand Down Expand Up @@ -171,4 +179,15 @@ private function needsQuoting(string $propertyName): bool
{
return !preg_match('/^[a-zA-Z0-9$_]+$/', $propertyName);
}

private function appendGlobalThis(string $type, array $reservedNames): string
{
foreach ($reservedNames as $reservedName) {
if (str_starts_with($type, $reservedName)) {
return 'globalThis.' . $type;
}
}

return $type;
}
}

0 comments on commit 7e571db

Please sign in to comment.