パターン マッチングを使用して、外部 JSON 呼び出しの結果のオプション プロパティから値を安全に抽出できるようにしたいと考えています。
シナリオ: (ランダムな例として openweathermap api を使用)
type MyType = { cod: int option }
let printCod (x:MyType) = match x.cod with
| Some cod -> Console.Log(cod)
| None -> Console.Log("EMPTY")
let success =
fun (data, _, _) ->
let dat = As<MyType> data
Console.Log(dat.cod.IsSome) // prints false
Console.Log(dat.cod.IsNone) // prints false
Console.Log(dat.cod) // prints correct value
printCod dat // prints undefined
let dat' = {cod = Some 300}
Console.Log(dat'.cod.IsSome) // prints true
Console.Log(dat'.cod.IsNone) // prints false
printCod dat' // prints 300
let dat'' = {cod = None}
printCod dat'' // prints Empty
let config =
JQuery.AjaxConfig
(Url = "http://api.openweathermap.org/data/2.5/weather?q=London,uk",
DataType = (JQuery.DataType.Jsonp :?> _), Success = [| success |])
let AjaxCall() = JQuery.JQuery.Ajax(config)
let Main =
let _ = AjaxCall()
...
Option を使用して、応答オブジェクトを自分のタイプに応じて正しく処理できるようにしたいと考えています。ご覧のとおりAs<T>
、このシナリオでは変換が十分ではありません。適切な解決策が見つかりません。
これに対する適切な回避策はありますか?
注: Websharper 3.0 を使用しています