adamko-dev/kotlinx-serialization-typescript-generator

Provide an easier way to set default TypeScript elements, so generated code can be customised more easily

aSemy opened this issue · 0 comments

aSemy commented

If a client already has some standard type aliases, then I want to re-use those type aliases in my generated code.

@Serializable
data class Position(
  val x: Double,
  val y: Double,
)
// provided by library
export type double = number

// I want generated code to use 'double'
export interface Position {
  x: double;
  y: double;
}

If I hack around a bit, I can come up with something that works. But it's not pretty, or intuitive

fun main() {
  val tsGenerator = KxsTsGenerator()

  val libraryDoubleTypeRef = TsTypeRef.Declaration(TsElementId("Double"), null, false)

  tsGenerator.descriptorElements += Double.serializer().descriptor to setOf(
    TsDeclaration.TsTypeAlias(
      TsElementId("Double"),
      TsTypeRef.Declaration(TsElementId("double"), null, false),
    )
  )

  tsGenerator.descriptorTypeRef += mapOf(
    Double.serializer().descriptor to libraryDoubleTypeRef
  )

  println(tsGenerator.generate(Position.serializer()))
}

@Serializable
data class Position(
  val x: Double,
  val y: Double,
)

This produces the correct output...

export interface Position {
  x: Double;
  y: Double;
}

export type Double = double;

Good luck figuring that out if you're new to KXS, and didn't happen to build this library...

Potential solutions

Users should be able to set overrides for SerialDescriptors, similar to the existing serializerDescriptors and descriptorElements in KxsTsGenerator. For example

val gen = KxsTsGenerator()

gen.addOverride(
  Double.serializer().descriptor to existingTypeAlias("double"),
)