Katxupa
  • 👋Welcome to Katxupa Extension Library
  • Why Katxupa?
    • 🍻What makes Katxupa special?
    • ✨Key Features
  • Get a taste of Katxupa
    • 🍲Installation
    • 🍜Usage
      • 🍻Scope Functions
        • Function Selection
        • Distinctions
        • Functions
          • letIt
          • withIt
          • runIt
          • applyIt
          • alsoIt
          • takeIf and takeUnless
      • 😎Null Safety
        • TypeScript Null-Safety
        • Optional Chaining for JavaScript
      • ⏰Duration
      • ➖Reducer
      • 📏Range
      • 🏃‍♂️Result
      • 🤼Either
      • 🟰Compare
      • ⚔️Global Utility Functions
    • 🤌Dip Dive
      • Optional
      • Range
      • Duration
      • Reducer
      • Collections
        • Array
        • Set
  • 🙏Support
    • Source Code
    • ESLint Config
    • TypeScript Docs
    • Manuel Santos Linkedin
Powered by GitBook
On this page
  1. Get a taste of Katxupa
  2. Usage

Null Safety

PrevioustakeIf and takeUnlessNextTypeScript Null-Safety

Last updated 1 year ago

Null-safety refers to the language's features and practices that aim to prevent or mitigate the issues associated with null and undefined values. TypeScript has introduced stricter null-checking capabilities to enhance the overall safety and robustness of the code.

These collectively contribute to a more robust null-safety mechanism in TypeScript, reducing the likelihood of null-related runtime errors. However, it's important for developers to understand and apply these features appropriately to ensure code correctness and safety.

So, what can Katxupa provide on top of this?

  1. First of all, one big advantage of Katxupa is to bring functional programming paradigm through scope functions and type extensions. To keep the flow, you can make use of (?.) when using scope functions to ensure null-safety:

// Only run the code block if "numberOrUndefined" is defined 
const numberOrUndefinedOrNull = await bitcoinService.getPrice();
numberOrUndefinedOrNull?.letIt((it) => {
    it++;
    it = it * 100;
    return it;
});

// Actually, there is no need to declare a variable
(await bitcoinService.getPrice())
    ?.letIt((it) => {
        it++;
        it = it * 100;
        return it;
    });// Some code
  1. Secondly, dealing with null and undefined values can be improved by using the Optional concept. Optional gives the power to differentiate between the absence of a value and the null or undefined reference. So, Optional is a wrapper utility that provides a way to handle potentially null or undefined values in a concise and expressive manner. It also allows various operations on the value, such as checking if it is present, retrieving it, applying transformations and handling empty values.

// Example 1
// Get Usecase:
//    1- Validate if user exists
//    2- Through an HttpError if not 
//    3- Return the user object
return optionalOf(user)
    .orElseThrow(() => new NotFoundError("User doesn't exist"))
    .get();

// Example 2
// Delete Usecase:
//    1- Validate if user exists
//    2- Through an HttpError if not 
//    3-  Delete the user from the database asynchronously and await for the result
await Optional.of(user)
  .orElseThrow(() => new HttpError(409, "User doesn't exist"))
  .runAsync(() => this.userRepository.delete({id: userId}));

// Example 3
// Update usecase:
//    1- Validate if user exists
//    2- Through an HttpError if not
//    3- If exists, merge the existing one with additional userData
//    4- Call the user repository and save the updated user asyncronously, returning a promise
//            
return optionalOf(user)
    .orElseThrow(() => new HttpError(409, "User doesn't exist"))
    .map(user => {
        return {
            ...user,
            userData,
        };
    })
    .runAsync(user => this.userRepository.save(user));

Please also have a look in the following links to have a dip dive into the topic.

🍜
😎
features
Optional Chaining Operator
Optional
TypeScript Null-Safety