To install the latest version:
npm i duck-fp
Install ts-namespace-import-plugin:
npm i -D @unsplash/ts-namespace-import-plugin
Extend from namespaces tsconfig:
// tsconfig.json
{
"extends": "./node_modules/duck-fp/tsconfig.namespaces.json"
}
Use project typescript version in vscode press Ctrl + Shift + p then running TypeScript: Select TypeScript Version command, and selectin Use Workspace Version refering to this
- Imagine you have a piece of text that represents data in JSON format (like a configuration file or an API response).
- The parse function takes this text as input.
- Inside the function, it tries to convert the text into a JavaScript object using JSON.parse.
- If successful, it returns the either
right
parsed object. - If there’s an issue (for example, the text isn’t valid JSON), it returns either
left
containing Error instead. - We are using toError function that takes anything then stringifies it and
wraps in
Error
to handle catch block - Why Use This?
- The tryCatch approach is useful because it gracefully handles potential errors without crashing our program using
Either
monad. It’s like saying, “Hey, let’s try to parse this JSON, and if anything goes wrong, we’ll handle it gracefully.”
- The tryCatch approach is useful because it gracefully handles potential errors without crashing our program using
import { toError, tryCatch } from 'duck-fp/either'
const parse = (text: string) => {
return tryCatch(() => JSON.parse(text), toError)
}
The MIT License (MIT)