Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/alnorris/returnit
Stop throwing errors, and return type safe results
https://github.com/alnorris/returnit
Last synced: 5 days ago
JSON representation
Stop throwing errors, and return type safe results
- Host: GitHub
- URL: https://github.com/alnorris/returnit
- Owner: alnorris
- License: mit
- Created: 2023-11-03T12:36:55.000Z (about 1 year ago)
- Default Branch: main
- Last Pushed: 2024-09-23T20:28:54.000Z (about 2 months ago)
- Last Synced: 2024-10-29T00:54:07.580Z (17 days ago)
- Language: TypeScript
- Homepage:
- Size: 75.2 KB
- Stars: 1
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# returnit
Stop throwing errors, and return type safe results!
## Features
- Inferred const types without any explicit returns!
- Golang style returns
- Errors will return real error objects but extended with string literal codes that act as error enum codes.## Notes
- Please have `strictNullChecks` to true in your tsconfig.json## Install
- `npm i returnit`## How to use
```ts
import { Ok, Err } from 'returnit'export const login = asnyc (username: string, password: string, ip: string) => {
const user = await db.getUser(username)
if(!user) {
return Err('WRONG_PASSWORD')
}const isEqual = compareHash(dbUser.password, password)
if(!isEqual) {
return Err('WRONG_PASSWORD')
}if(loginRateLimited(username, ip)) {
return Err('RATE_LIMITED')
}return Ok(user)
}// ...
const [user, err] = await login('user', 'password', 127.0.0.0)
if(err) {
/*
`user` will undefined
`err` will be an Err object that the code field with string literal union of 'WRONG_PASSWORD' | 'RATE_LIMITED'Type narrowing mean you will get the correct type, and Either `user` or `err` will be defined, but not both at the same time.
*/
} else {
/*
result is the User object, and will be typed to it.
err here will equal type undefined
*/
}```
### All
Works similar to Promise.all, it accepts returnit type functions and executes them concurrently. It will return immediately if one of them returns an error, otherwise will return an array of the successful result.
```ts
import { Ok, Err, All } from 'returnit'const [result, err] = await All([returnIt1(),returnIt2()])
if(err) {
/*
err returns the first error encountered.
*/
} else {
/*
result is an array of the success results
*/
}```