Skip to main content

Inline value classes

Value classes are transformed to type aliases. The type of the value class is used.

@Serializable
@JvmInline
value class AuthToken(private val token: String)

fun main() {
val tsGenerator = KotlinTsGenerator()
println(tsGenerator.generate(AuthToken.serializer()))
}

You can get the full code here.

export type AuthToken = string;

Value classes from other libraries are also transformed to their inner types. For example, Kotlin unsigned numbers.

import kotlinx.serialization.builtins.serializer

fun main() {
val tsGenerator = KotlinTsGenerator()
println(
tsGenerator.generate(
UByte.serializer(),
UShort.serializer(),
UInt.serializer(),
ULong.serializer(),
)
)
}

You can get the full code here.

export type UByte = Byte;

export type UShort = Short;

export type UInt = Int;

export type ULong = Long;

export type Byte = number;

export type Short = number;

export type Int = number;

export type Long = number;

This weakens the unsigned numbers, and the generated TypeScript could be used to produce incompatible numeric values.

Brand typing​

To make value classes a little more strict, we can use brand typing

import io.github.esafak.kotlintsgen.KotlinTsConfig.TypeAliasTypingConfig.BrandTyping
import kotlinx.serialization.builtins.serializer

fun main() {

val tsConfig = KotlinTsConfig(typeAliasTyping = BrandTyping)

val tsGenerator = KotlinTsGenerator(config = tsConfig)
println(
tsGenerator.generate(
ULong.serializer(),
)
)
}

You can get the full code here.

export type ULong = Long & { __ULong__: void };

export type Long = number & { __Long__: void };

Now numeric types must be manually converted type aliases.

This does not mean

Nested value classes​

If the value class contains another value class, then the outer class will be aliased to other value class

@Serializable
@JvmInline
value class UserCount(private val count: UInt)

fun main() {
val tsGenerator = KotlinTsGenerator()
println(tsGenerator.generate(UserCount.serializer()))
}

You can get the full code here.

export type UserCount = UInt;

export type UInt = Int;

export type Int = number;