duck type in fsharp and interoping with js

Viewed 57

I'm using fsharp's fable compiler to interact with js.

Suppose js passes an object to fsharp, but we don't know what type it is, only that it may have some properties.

In js, we can ignore the type of the object and access its properties directly,

for js code example:

let msgheader = {
format: "standard",
sender: "tab",
receiver: "popup",
msg: {"content": "hello popup"}
id:2456
}

let {msg} = msgheader 
//msg: {"content": "hello popup"}

In fsharp, how can we access the properties directly when we don't know the type of the object?

In the case where the corresponding type cannot be defined, (for example, the format of the js object is not the same every time it is passed, sometimes it has "type" and "content", sometimes it may be a string) how should fsharp get the type or string of these js objects?

1 Answers

You can find information about this in the Fable documentation page Call JS from Fable. In particular, look at the Dynamic typing section.

The most primitive option is to use the dynamic access operator ? which can be used as follows (copied from the docs):

open Fable.Core.JsInterop

printfn "Value: %O" jsObject?myProperty

let pname = "myProperty"
printfn "Value: %O" jsObject?(pname) // Access with a reference

jsObject?myProperty <- 5 // Assignment is also possible

For checking if you have a string value or something else, you could use the Erased union approach, also documented on the Fable page.

Related