@as decorator with the @get decorator not working as expected

I’m using the @as decorator with @get as follows:

type t

@new external make: unit => t = "XMLHttpRequest"

@get
external status: t => @int
[
  | @as(200) #Ok
  | @as(400) #BadRequest
  | @as(401) #Unauthorized
  | @as(403) #Forbidden
  | @as(404) #NotFound
  | @as(500) #InternalServerError
] = "status"

let xhr = make()
let s = switch xhr->status {
| #Ok => "Ok"
| _ => "Other"
}
Js.log(s)

Which produces:

var xhr = new XMLHttpRequest();
var match = xhr.status;
var s = match === "Ok" ? "Ok" : "Other";
console.log(s);

However I was hoping to see:

var xhr = new XMLHttpRequest();
var match = xhr.status;
var s = match === 200 ? "Ok" : "Other"; // <==== 200 value here
console.log(s);

When using @as with @val it seems to work for me:

@val external setStatus: @int
[
  | @as(200) #Ok
  | @as(500) #InternalServerError
] => unit = "setStatus"

setStatus(#Ok)

Which produces:

setStatus(200);

But for now I am looking to have the @get behaviour working.

Any suggestions on what I might need to do in this case?

Thanks

Since you have no guarantee that the response will be among the ones you have listed, @int and equivalent are only usable for input parameters. If you want to have something like that in the return value, you’d better just write your own converter. Or you can bind to statusText using regular polymorphic variants to compile to plain strings anyway.

1 Like

@tsnobip yes that makes sense, thanks :pray: