onsreo
TypeScript icon, indicating that this package has built-in type declarations

1.0.6 • Public • Published

Option-None-Some-Result-Err-Ok


Provides types and helpers for JS/TS variants of Rust's Option & Result

How to use Option, Some, & None


import { is_some, is_none, all_some, all_none, Option } from 'onsreo';

let foo: [Option<number>, Option<number>, Option<string>, Option<string>] = [1, 2, null, "hi"];
let bar = foo[1];
let baz = foo[2];

// test to see if `bar` which is `Option<number>` is `Some<number>`
if(is_some(bar){
  // `bar` seen as `number` i.e., `Some<number>`
} else {
  // `bar` seen as `None` i.e., null
}

// test to see if `baz` which is `Option<string>` is `None`
if(is_none(baz){
  // `baz` seen as `None` i.e., null
} else {
  // `baz` seen as `string` 
}

// test if an option tuple is all `Some`
if(all_some(foo)){
  foo // seen as `[number, number, string, string]`
} else {
  foo // seen as current type
}

// test if an option tuple is all `None`
if(all_none(foo)){
  foo // seen as `[None, None, None, None]`
} else {
  foo // seen as current type
}

How to use Result, Ok, & Err


import { is_ok, is_err, all_ok, all_err, Result } from 'onsreo';

class MyError extends Error {} // or whatever your custom error is

let foo: [
  Result<number>, // NOTE: defaults to `Error` if no specific class is specified 
  Result<number>, 
  Result<string, MyError>,
  Result<string, MyError>
] = [1, 2, new MyError(), "hi"];
let bar = foo[1];
let baz = foo[2];

// test to see if `bar` which is `Result<number>` is `Ok<number>`
if(is_ok(bar){
  // `bar` seen as `number` i.e., `Ok<number>`
} else {
  // `bar` seen as `Err` i.e., `Error`
}

// test to see if `baz` which is `Result<string, MyError>` is `Err<MyError>`
if(is_err(baz){
  // `baz` seen as `Err<MyError>` i.e., `MyError`
} else {
  // `baz` seen as `string`, i.e, Ok<string> 
}

// test if an option tuple is all `Ok`
if(all_ok(foo)){
  foo // seen as `[number, number, string, string]`
} else {
  foo // seen as current type
}

// test if an option tuple is all `None`
if(all_err(foo)){
  foo // seen as `[Error, Error, MyError, MyError]`
} else {
  foo // seen as current type
}

Package Sidebar

Install

npm i onsreo

Weekly Downloads

2

Version

1.0.6

License

MIT

Unpacked Size

24.6 kB

Total Files

17

Last publish

Collaborators

  • evjonell