I’m trying to write a wrapper for a JS library in ...
# javascript
a
I’m trying to write a wrapper for a JS library in Kotlin. There’s a function that returns a mapped type. How can I convert the result to a Kotlin type? I guess I should convert it to a
Map<String, String?>
?
Copy code
export default class Match {
  getNamedCaptures(): NamedCaptures;
}

export type Capture = string | null;
export type NamedCaptures = { [key: string]: Capture };
Found the answer in these threads: • https://discuss.kotlinlang.org/t/how-to-access-native-js-object-as-a-map-string-any/509/8https://stackoverflow.com/questions/47921255/what-is-simple-way-to-convert-dynamically-kotlin-js-objects-to-plain-javascript
Copy code
internal external class Match {
  /**
   * Fetches all named captures, without their indices.
   */
  fun getNamedCaptures(): NamedCaptures
}

/** `export type NamedCaptures = { [key: string]: string | null };` */
external interface NamedCaptures

private fun entriesOf(obj: dynamic): Map<String, Any?> {
  return (js("Object.entries") as (dynamic) -> Array<Array<Any?>>)
    .invoke(obj)
    .associate { (name, entry) -> name as String to entry }
}

fun NamedCaptures.toMap(): Map<Any?, Any?> {
  return entriesOf(this)
    .mapValues { (_, v) -> v as String? }
}