traverse1984 / oxide.ts

Rust's Option<T> and Result<T, E>, implemented for TypeScript.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

using match to return a Result gives an error

joelgrus opened this issue · comments

it seems like the following should work?

function unpack(res: Result<Option<string>, Error>): Result<string, Error> {
  return match(res, {
    Ok: {
      Some: (x) => Ok(x),
      None: () => Err(new Error('not found')),
    },
    Err: (e) => Err(e),
  })
}

but it results in an error

error TS2322: Type '{ Some: (x: string) => Ok<string>; None: () => Err<Error>; }' is not assignable to type 'MonadMapped<Option<string>, Err<Error>>'.
      Types of property 'Some' are incompatible.
        Type '(x: string) => Ok<string>' is not assignable to type 'MonadMapped<string, Err<Error>>'.
          Type '(x: string) => Ok<string>' is not assignable to type 'Mapped<string, Err<Error>>'.
            Type 'Ok<string>' is not assignable to type 'Err<Error>'.
              Type 'string' is not assignable to type 'never'.

am I doing something wrong? or is there a better way to accomplish this sort of thing?

better way:

function unpack(res: Result<Option<string>, Error>): Result<string, Error> {
  return res.map((opt) => match(opt, 
    { 
      Some: (s) => s,
      None: () => { throw new Error('not found') }
    }))