Skip to content

Commit

Permalink
Use as const in TypeScript generator
Browse files Browse the repository at this point in the history
It looks like `discriminator = 3 as const` lets tsc make somewhat more correct type inferences than `discriminator: number = 3 as 3`.
  • Loading branch information
lynn authored Nov 1, 2024
1 parent 58cc476 commit 6b5fe72
Showing 1 changed file with 3 additions and 4 deletions.
7 changes: 3 additions & 4 deletions Core/Generators/TypeScript/TypeScriptGenerator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -737,14 +737,13 @@ public override ValueTask<string> Compile(BebopSchema schema, GeneratorConfig co
{
if (td.OpcodeDecorator is not null && td.OpcodeDecorator.TryGetValue("fourcc", out var fourcc))
{
builder.AppendLine($"public static readonly opcode: number = {fourcc} as {fourcc};");
builder.AppendLine($"public static readonly opcode = {fourcc} as const;");
}
if (td.DiscriminatorInParent != null)
{
// We codegen "1 as 1", "2 as 2"... because TypeScript otherwise infers the type "number" for this field, whereas a literal type is necessary to discriminate unions.
builder.AppendLine($"public readonly discriminator: number = {td.DiscriminatorInParent} as {td.DiscriminatorInParent};");
builder.AppendLine($"public readonly discriminator = {td.DiscriminatorInParent} as const;");
// back compaq for v2 usage where discriminator is a static field
builder.AppendLine($"public static readonly discriminator: number = {td.DiscriminatorInParent} as {td.DiscriminatorInParent};");
builder.AppendLine($"public static readonly discriminator = {td.DiscriminatorInParent} as const;");
}
for (var i = 0; i < fd.Fields.Count; i++)
{
Expand Down

0 comments on commit 6b5fe72

Please sign in to comment.