Tips for exporting class methods in TypeScript

I've created a TypeScript class that looks like this:

 class User {
  static readAll(): Promise<IUser[]> {
    return new Promise((resolve, reject) => {
      connection.query<IUser[]>("SELECT * FROM users", (err , res) => {
        if (err) reject(err)
        else resolve(res)
      })
    })
  }

  static readById(user_id: number): Promise<IUser | undefined> {
    return new Promise((resolve, reject) => {
      connection.query<IUser[]>(
        "SELECT * FROM users WHERE id = ?",
        [user_id],
        (err, res) => {
          if (err) reject(err)
          else resolve(res?.[0])
        }
      )
    })
  }

  static create(req : Request) : Promise<IUser> {
    return new Promise((resolve, reject) => {
      connection.query<OkPacket>(
        "INSERT INTO users (email, password, admin) VALUES(?,?,?)",
        [req.body.email, req.body.password, req.body.admin],
        (err, res) => {
          if (err) reject(err)
          else
            this.readById(res.insertId)
              .then(user => resolve(user!))
              .catch(reject)
        }
      )
    })
  }

  static update(user: IUser): Promise<IUser | undefined> {
    return new Promise((resolve, reject) => {
      connection.query<OkPacket>(
        "UPDATE users SET email = ?, password = ?, admin = ? WHERE id = ?",
        [user.email, user.password, user.admin, user.id],
        (err, res) => {
          if (err) reject(err)
          else
            this.readById(user.id!)
              .then(resolve)
              .catch(reject)
        }
      )
    })
  }

  static remove(user_id: number): Promise<number> {
    return new Promise((resolve, reject) => {
      connection.query<OkPacket>(
        "DELETE FROM users WHERE id = ?",
        [user_id],
        (err, res) => {
          if (err) reject(err)
          else resolve(res.affectedRows)
        }
      )
    })
  }
  
}

However, I'm struggling to import these methods into another file directly. I currently have to instantiate a User object in order to access the methods like User.create(). Is there a better way to export these methods so they can be easily imported and used in other files?

I'm uncertain how to properly export these methods so they can be imported seamlessly into another file.

Answer №1

When working with JavaScript / TypeScript, it is not necessary to include independent functions as static methods within a container class, which sets it apart from Java.

If your connection variable is accessible within the scope, you can simply use:

// user.ts
const connection = // database connection instance...

export function readAll() { /* ... */ }

// In another file
import { readAll } from "./user";

readAll();

Furthermore, even if you decide to have a container class containing static methods, you do not need to actually create an instance of the class in order to utilize its static methods (similar to Java):

// user.ts
export class User {
  static readAll() { /* ... */ }
}

// In another file
import { User } from "./user";

User.readAll(); // No instantiation required (new User())

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

An infinite number of data requests are initiated asynchronously within a loop

When using Angular with TypeScript, I have the following component class: @Injectable() @Component({ selector: 'app-mycomponent', templateUrl: './mycomponent.component.html' }) export class MyComponent implements OnInit{ p ...

Vue textarea not accepting null values

My current setup includes the following dependencies: - "vue": "3.2.26", - "vee-validate": "4.5.6", - "typescript": "4.5.4" While working on a textarea field in vue3, I encountered an issue Here's a snippet with vee-validate integration import { Fie ...

Using AngularJS to inject a service into a static property of a standard class

For my current project, I am combining TypeScript and AngularJS. One of the challenges I'm facing is how to instantiate a static member of a public class (not controller, just a normal class) with a service object. When it comes to controllers, utiliz ...

Using NestJS to import and inject a TypeORM repository for database operations

This is really puzzling me! I'm working on a nestjs project that uses typeorm, and the structure looks like this: + src + dal + entities login.entity.ts password.entity.ts + repositories ...

There appears to be no overload that aligns with this call using styled components (index.d.ts(2187, 9))

Trying to create an Input component using styled components that accepts props but encountering an error when using the onChange prop - No overload matches this call. It seems like there might be an issue with my types, but even after extensive research, I ...

I am confused about the term "can only be default-imported using the 'esModuleInterop' flag", could you explain it to me?

I ran into a puzzling error: lib/app.ts:1:8 - error TS1259: Module '"mongoose-sequence"' can only be default-imported using the 'esModuleInterop' flag and it seems to be related to this line of code: import _ from 'mongoose-sequ ...

Having trouble retrieving input values from forms in Angular 2?

Currently, I am using a modal form that loads information about my items when it is open. However, when I try to submit, all inputs are null except when the modal displays which works fine. <div id="modal1" class="modal"> <form #formData=' ...

Integrating d3.js into an Angular 2 project

Trying to incorporate the d3.js library into a MEAN application using angular2. Here are the steps I've taken: npm install d3 tsd install d3 In mypage.ts file (where I intend to show the d3.js graph) // <reference path="../../../typings/d3/d3.d ...

Retain the Previously Selected Option in Angular 2 Dropdown

Looking for assistance with implementing a simple HTML select dropdown in Angular2 (TS) using the code below: <select id="pageSize" (change)="onPageSizeChanged($event, pagination.pageSize)"> <option value="10">10</option> <option ...

Exploring the power of global injectors in Angular 7 for component inheritance

Recently, I have been following a method outlined in a blog post on MSDN to simplify the extension of components without having to include all dependencies in the super() call. However, this approach seems to have ceased working in Angular 7 with Typescrip ...

Why is the value not being assigned by the Angular component from the observable service getter?

I am currently working on developing a filter set, and I am facing an issue with the salesChannels array content in my view. The array only gets populated after clicking a button that triggers the test() function. Interestingly, the first time I log the ar ...

Retrieve the callback function assigned to an eventEmitter in Angular 4

Is there a way to retrieve the function passed to the Event Emitter? Within my component, I am passing a function to an event emitter as shown below: <component (onClick)='function(parameter)'></component> I have set up an @Output ...

Create type declarations using the Typescript compiler by running the command:

After generating my definition file ".d.ts" using tsc --declaration or setting declaration as true in the tsconfig.json, I noticed that the generated files are missing declare module "mymodule" {... } This appears to be causing issues with "tslint" which ...

Frequently found items in TypeScript

I need help incorporating a global object in TypeScript for my application. Specifically, I want to have user details available and bindable throughout the entire application after a remote call. Can someone provide an example of how this can be achieved? ...

Setting default values for HOCs in React

If I have a higher order component structure like this: interface MyHOCInterface { title: string } export function wrapMyHoc<T extends MyHOCInterface>( Component: React.ComponentType<T>,) { return class extends React.Component<T> { ...

Extract the Top X elements from a multidimensional array

Consider an Array that consists of nested arrays: [ ["2000-01-01", "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d1a9a8abe091b6bcb0b8bdffb2bebc">[email protected]</a>", 1, 9, 338], ["2000-01-01", "<a href="/ ...

Angular File Upload Button Tutorial

English is not my first language, so please excuse any mistakes. I recently started learning Angular and I'm attempting to build a file upload button that lets users upload files based on dropdown menu options (such as USA States). Once uploaded, the ...

Table-driven forms in Angular

I am facing a requirement where I need to submit a form containing five records in a table format. Here is how the table looks: https://i.sstatic.net/82ZFM.png This is the code snippet for the form: <form [formGroup]="FeedBack" (ngSubmit)=&q ...

What is the best way to obtain an attribute name that is reminiscent of Function.name?

My objective is to securely type an attribute. For example, I have an object: const identity = { address: "Jackie" }; At some point, I will rename the address key to something else, like street_address. This is how it is currently implemented ...

Encountered an issue when making an Angular2 HTTP POST request - SyntaxError: JSON input unexpectedly ended

Encountering an issue while trying to post data from Angular2 to a NodeJS backend. Although the POST request is successful and the server logs the correct data, an error is displayed in the browser: An error occurred: SyntaxError: JSON.parse: unexpected ...