Security News
pnpm 10.0.0 Blocks Lifecycle Scripts by Default
pnpm 10 blocks lifecycle scripts by default to improve security, addressing supply chain attack risks but sparking debate over compatibility and workflow changes.
@andrejewski/result
Advanced tools
A result type written in TypeScript
npm install @andrejewski/result
import { Result, ok, err } from '@andrejewski/result'
function parseJSON (json: string): Result<unknown, SyntaxError> {
try {
return ok(JSON.parse(json))
} catch (error) {
if (error instanceof SyntaxError) {
return err(error)
}
throw error
}
}
const parseResult = parseJSON('{"foo": "bar"}')
const fooResult = parseResult.andThen(value => {
if (!(value && value.foo && typeof value.foo === 'string')) {
err(new Error('Field `foo` must be of type string'))
}
return ok(value.foo)
})
const foo = fooResult.match({
ok (value) {
return value
},
err (error) {
throw error
}
})
See the type definitions and code comments for detailed documentation.
There's only two ways to create result types: ok
and err
.
Nice and short: no need to use new Result(x, y)
, new Ok(x)
, etc.
To let Typescript help us, we enable type guards via discriminated unions on multiple fields, so we can write clean branches:
import { Result, ok } from '@andrejewski/result'
const result = ok(1) as Result<number, never>
// Type guard using `type` property
if (result.type === 'ok') {
// We can now access `value`
console.log(result.value)
} else {
// We can now access `error`
console.log(result.error)
}
// Type guard using `isOk` property
if (result.isOk) {
// We can now access `value`
console.log(result.value)
} else {
// We can now access `error`
console.log(result.error)
}
// Type guard using `isErr` property
if (result.isErr) {
// We can now access `error`
console.log(result.error)
} else {
// We can now access `value`
console.log(result.value)
}
Hey now, lack of features is totally a feature!
unwrap
You'll notice I didn't add some "niceties" like Result#unwrap
, which throws the err component and returns the ok component of a result.
Including those methods makes it too easy to use them internally whereas they should really only be used, if at all, at the edges of a system.
Folks can build there own on top but the friction of doing so is a feature.
toJSON
We don't provide any common mechanism for JSON de/serialization because it has many quirks. These can be built on top but don't need to be in this package.
try
sugarIf you are coming from Rust, you'll have loved the result?
unwrapping sugar. Unfortunately that type of sugar, even as written as unwrap(result)
instead of a macro, is not going to be helped by TypeScript. Simply put, there's no good way to have a good error type derived from successive calls of a function:
const result = Result.try(unwrap => {
const a = unwrap(fnErrorsA())
const b = unwrap(fnErrorsB(a))
return ok(nonResultFn(b))
})
Here, the best we could do is result
having type Result<typeof b, unknown>
but that's not good enough!
I don't wanna have to re-check for all the potential errors.
So we don't include any syntactic sugar to make this easier, preferring correctness and precise types.
There are alternatives to this package's take on result type. Here are some and why I'm not using them:
result
:.then
and .node
smatter against Promise and callback asynchronyresult-js
result.isOk()
that can't type guardfromSuccess
and fromError
which mismatch ok
/err
namingunwrap*
methods which make it too easy to use exceptionstypescript-result
err
type to Error
which need not be the caseerr
type on the leftmost type parameter which is very confusing to readResult.safe
methodts-results
Option
type which isn't needed in JavaScript/Typescriptok.val
is the same in err.val
meaning you don't need to narrow the type to access the value, and you might forget to do thatexpect
and unwrap
methods which encourage exceptionsFAQs
Result type
We found that @andrejewski/result demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
pnpm 10 blocks lifecycle scripts by default to improve security, addressing supply chain attack risks but sparking debate over compatibility and workflow changes.
Product
Socket now supports uv.lock files to ensure consistent, secure dependency resolution for Python projects and enhance supply chain security.
Research
Security News
Socket researchers have discovered multiple malicious npm packages targeting Solana private keys, abusing Gmail to exfiltrate the data and drain Solana wallets.