From 6b5fe723f3953795b2835607365c3d3a7f4e555e Mon Sep 17 00:00:00 2001 From: Lynn Date: Fri, 1 Nov 2024 14:49:50 +0100 Subject: [PATCH] Use `as const` in TypeScript generator It looks like `discriminator = 3 as const` lets tsc make somewhat more correct type inferences than `discriminator: number = 3 as 3`. --- Core/Generators/TypeScript/TypeScriptGenerator.cs | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/Core/Generators/TypeScript/TypeScriptGenerator.cs b/Core/Generators/TypeScript/TypeScriptGenerator.cs index a1555e02..6a42315f 100644 --- a/Core/Generators/TypeScript/TypeScriptGenerator.cs +++ b/Core/Generators/TypeScript/TypeScriptGenerator.cs @@ -737,14 +737,13 @@ public override ValueTask 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++) {