Example 1
This code defines a function in TypeScript that searches for a user by name in a list of users. If the user is not found, it throws a custom error. The users array, which is supposed to contain the user data, is assumed to exist but is not explicitly shown in the code.
Let's break down the code step by step:
1. import { ProjectError } from '@sirutils/core'
This line imports a ProjectError class or object from the @sirutils/core module. This class is used to create custom error messages.
2. const getUser = (name: User["name"]) => {...}
This line defines a function named getUser. The function takes a parameter name of type User"name", which is defined on above as part of a User type or interface.
3. const found = users.find(user => user.name === name)
This line searches through the users array. This array contains user objects, each with at least a name property. The find method searches for the first user whose name matches the name parameter and assigns it to the found variable. If no user is found, found will be undefined.
4. if(!found) { ... }
This checks whether found is undefined. If it is, meaning the user was not found, a custom error is thrown.
5. return ProjectError.create("?get-user", "user not found").throw()
This line creates a new error using the ProjectError class. The error is created with a code "?get-user" and the message "user not found". The .throw() method then immediately throws this error, causing the getUser function to throw an error if the user is not found.
6. return found
If the user is found, the found variable (which contains the user object) is returned.
Usage Example:
If a user with the name "alice" exists in the users array, that user's object is logged to the console.
If no user with the name "eugeo" is found, a ProjectError is thrown and this error is logged to the console.