Home > other >  How to export class methods in TypeScript?
How to export class methods in TypeScript?

Time:01-04

I have a class written in TypeScript like following:

 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)
        }
      )
    })
  }
  
}

But I can't import methods that are defined inside of it( like readAll, creqate, etc.) inside another file. The only way I can do that is to create a User instance then access the methods like User.create() but I am not sure if this is the only way, or even a right way of doing it?

Actually I don't know how to export methods like they could be importable within another file?

CodePudding user response:

In JavaScript / TypeScript, you do not have to put independent functions as static methods of a container class, unlike Java for example.

Assuming your connection variable is in scope, you could do:

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

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

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

readAll();

BTW, even if you keep a container class with static methods, you should not need to instantiate the class to use its static methods (same in Java):

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

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

User.readAll(); // No instantiation (new User())
  • Related