Retrieve a specific category within a method and then output the entire entity post adjustments

I need to sanitize the email in my user object before pushing it to my sqlite database. This is necessary during both user creation and updates. Here's what I have so far:

export const addUser = (user: CreateUser) => {
  db.prepare(sqlInsertUser).run(cleanEmail(user))
}

export const updateUser = (user: UpdateUser) => {
  db.prepare(sqlUpdateUser).run(cleanEmail(user))
}

type CreateUser = {
  email: string
  password: string
  permissionLevel?: number
}

type UpdateUser = {
  email: string
  password: string
}

Now, I'm working on:

const cleanEmail = (user: ?) => {
  user.email = user.email.trim()
  return user
}

However, I'm unsure of what type to assign to the 'user' parameter. How do I handle multiple types and return the updated object?

Is there a way to implement this effectively, even with additional types that all include the email property?

Answer №1

If you have a generic type that requires an email property as a string, you can use the following function:

function cleanEmail<T extends { email: string }>(user: T): T {
  user.email = user.email.trim();
  return user; // The return type is inferred as 'T'
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the method for typing an array of objects retrieved from realmDB?

Issue: Argument type 'Results<Courses[] & Object>' cannot be assigned to the parameter type 'SetStateAction<Courses[]>'. Type 'Results<Courses[] & Object>' lacks properties such as pop, push, reverse, ...

Angular button for opening or closing the menu that redirects the page to a localhost URL

I have implemented a template from the link below into my project. So far, everything has been working fine, but recently I noticed that the menu open/close button is malfunctioning. Whenever I click on the close button while on any page (for example, http ...

Error: Unable to access the 'replace' property of an object that is not defined during object instantiation

Check out my class and interface below: export interface Foo{ numFoo: string } export class Blah{ constructor( public numBlah: string, public arrayOfFoos: Array<Foo>, public idBlah: string ) { } } let numBlah: string = ' ...

Combining Typescript interfaces to enhance the specificity of a property within an external library's interface

I have encountered a scenario where I am utilizing a function from an external library. This function returns an object with a property typed as number. However, based on my data analysis, I know that this property actually represents an union of 1 | 2. Ho ...

How can we utilize Typescript to check if the intern 4 page has finished loading?

I've managed to set up a function in intern 4 using TypeScript that waits for the page to load. However, there are instances where it doesn't work and throws a TimeOutError even when I catch the error within the function. Can someone please take ...

Leveraging CSS attribute selectors within JSX using TypeScript

With pure HTML/CSS, I can achieve the following: <div color="red"> red </div> <div color="yellow"> yellow </div> div[color="red"] { color: red; } div[color="yellow"] { color: yellow; ...

What is the best way for a function to accommodate various types that adhere to an interface?

How can we create a function that can accept multiple types with a common interface? Let's consider the example: interface A {a: number} type B = {b: string;} & A type C = {c: string;} & A function acceptA(a: A) { return a } acceptA({a ...

Tips for correctly decorating constructors in TypeScript

When a class is wrapped with a decorator, the superclasses lose access to that classes' properties. But why does this happen? I've got some code that demonstrates the issue: First, a decorator is created which replaces the constructor of a cla ...

What is the method for including as: :json in your code?

I have a file with the extension .ts, which is part of a Ruby on Rails application. The code in this file looks something like this: export const create = async (params: CreateRequest): Promise<XYZ> => { const response = await request<XYZ> ...

Setting a maximum limit for selections in MUI Autocomplete

Code updated to display the complete script logic. I want to restrict the number of selections based on a value retrieved from the database, but in this example, I have set it to 3 manually. The error message I'm encountering is "Cannot read properti ...

Compile time error due to TypeScript enumeration equality issue

Currently, I am developing a system to manage user roles within my website using TypeScript enumeration. This will allow me to restrict access to certain parts of the site based on the user's role. The primary challenge I am facing is comparing the u ...

When transmitting data from NodeJS, BackBlaze images may become corrupted

I have been facing a challenge in my React Native app where I am attempting to capture an image and then post it to my NodeJS server. From there, I aim to upload the image to BackBlaze after converting it into a Buffer. However, every time I successfully u ...

How can I manually listen to Angular 2 events on a dependency injected instance?

Assume I am working with a component: @Component({selector: 'todo-cmp'}) class TodoCmp { @Input() model; @Output() complete = new EventEmitter(); // TypeScript supports initializing fields onCompletedButton() { this.complete.next(); / ...

When using Styled Components with TypeScript, you may encounter the error message "No overload matches

Recently, I've delved into Style Components in my journey to create a weather app using React Native. In the past, I would typically resort to CSS modules for styling, but it appears that this approach is not feasible for mobile development. Below is ...

Utilizing a background image property within a styled component - Exploring with Typescript and Next.js

How do I implement a `backgroung-image` passed as a `prop` in a styled component on a Typescript/Next.js project? I attempted it in styled.ts type Props = { img?: string } export const Wrapper = styled.div<Props>` width: 300px; height: 300px; ...

Angular 14 captures typed form data as `<any>` instead of the actual data types

On the latest version of Angular (version 14), I'm experiencing issues with strictly typed reactive forms that are not functioning as expected. The form initialization takes place within the ngOnInit using the injected FormBuilder. public form!: For ...

Encountering a 404 error when importing http/server in deno

The file named index.ts is located below import { serve } from "https://deno.land/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b0c3c4d4f0809e8186869e80">[email protected]</a>/http/server.ts"; function ...

Encountering Error with NodeJS Typescript: Issue with loading ES Module when running sls offline command

I have come up with a unique solution using NodeJS, Typescript, and Serverless framework to build AWS Lambdas. To debug it locally in VS Code, I use the serverless-offline library/plugin. You can find my project on GitHub here However, when I run the comm ...

Is it possible to create a class object with properties directly from the constructor, without needing to cast a custom constructor signature

class __Constants__ { [key: string]: string; constructor(values: string[]) { values.forEach((key) => { this[key] = key; }); } } const Constants = __Constants__ as { new <T extends readonly string[]>(values: T): { [k in T[num ...

how to implement dynamic water fill effects using SVG in an Angular application

Take a look at the code snippet here HTML TypeScript data = [ { name: 'server1', humidity: '50.9' }, { name: 'server2', humidity: '52.9', }, { name: 'server3', humidity: ...