Do you know how can I get a JS object with the sam...
# javascript
m
Do you know how can I get a JS object with the same proto as plain JS object from a data class (
Object.getPrototypeOf(input) === Object.prototype
) ?
r
Could you please provide some details about your case? At the first look it seems like it is impossible.
m
yes, I create a wrapper for Firebase Firecloud. When I want to create a document, I must provide a JS object and when I provide a data class, I get an error. In the firebase code I found this method : https://github.com/firebase/firebase-js-sdk/blob/master/packages/firestore/src/util/input_validation.ts#L243 And I failed on this equality...
It works with a js object like
Copy code
val d: dynamic = object{}
d["name"] = "John"
d["age"] = 50
But it's ugly...
t
Maybe you could use serialization? You would convert your data class into plain javascript object 🤔
a
AFAIK the cleanest solution at the moment is something like this:
Copy code
external interface A {
    val name: String
    val age: Int
}

fun js(builder: dynamic.() -> Unit): dynamic {
    val result = Any().asDynamic()
    builder(result)
    return result
}

fun A(name: String, age: Int): A = js {
    this.name = name
    this.age = age
}

fun main(args: Array<String>) {
    val a = A("John", 20)
    
    println(a.name)
    println(a.age)
    
    println(js("Object.getPrototypeOf(a) === Object.prototype"))
}
External interface is nice to have in order to have your types in kotlin code while making it possible to implement is via a plain JS object under the hood. Factory function makes your instantiation look normal. A helper
js
builder makes JS Object creation a bit simpler.
Note that
Any()
is translated to
new Object()
t
But you will loose the convenience of a data class, no?
m
Ok, it's add a lot of code and like @Tristan Caron said, I loose the convenience of a data class. I'll try serialization, it could be the best with less code.
a
Good luck!
m
Th really quick way for this case (firestore check) :
JSON.parse(JSON.stringify(metadata))
It's a hack but we keep the convenience of data class.