What's the best way to use a string enum in a Kotl...
# javascript
q
What's the best way to use a string enum in a Kotlin/JS type definition? I'm using
Copy code
@JsExport enum class Animals { CAT, DOG }
but the typescript definition creates a class that doesn't serialize correctly. I would like the compile-time check here but at runtime it's enough for it to be a string so that it serializes correctly 🤔
a
@turansky ^^'
t
We use Seskar to describe string unions. Example
Will you export it? Use in TS library?
q
yes
Does it work with a multiplatform project? When I add it to my module, I get this error:
Copy code
An exception occurred applying plugin request [id: 'io.github.turansky.seskar', version: '2.66.0']
> Failed to apply plugin class 'seskar.gradle.plugin.SeskarReactPlugin'.
   > Configuration with name 'jsMainImplementation' not found.
t
It works :) For now you can use
apply(plugin=...)
in the end of your kts file.
q
Can this be exported? When I apply the
@JsExport
annotation I get an error (
Declaration of such kind (companion object inside exported interface) can't be exported to JS
)
e
I don't think it's exportable
q
I don't think it's exportable
Oh, I see. I wanted to provide some enum support so that the consumer of my library could have stronger typing and pass only valid strings to it. I guess the viable alternative is to export an object with the string enum and suggest consumers use it, even if I have to change the type to a string and can only validate it at runtime. For example:
Copy code
@JsExport
object PetType {
    val Dog = "DOG"
    val Cat = "CAT"
}

@JsExport
external interface Pet {
    val type: String
}

// ts
const pet: Pet = { type: PetType.Dog } // Not sure if you can call it like this
e
Maybe the enum serialization you mentioned can be fixed instead of going down another route?
q
That's not easy, the library takes an input and returns an output value that is serialized using
fast-json-stringify
. Because I'm code generating the data model, this is more complicated. That's why some built in way to restrict the options of the consumer of the library would be enough