K
K
komigor2021-07-10 07:35:34
typescript
komigor, 2021-07-10 07:35:34

How to pass the instace of an object to a function?

grow up for a stupid question, you just have to teach ts how to do it. How to pass an instance of an object to a function? Here in one file I extract the class instance like this

class ApiError extends Error{       
    
    constructor(status, message) {
            status: number;
            message: string;

            super();
              this.status = status
              this.message = message
          }
      
          static badRequest(message) {
              return new ApiError(404, message)
          }
      
          static internal(message) {
              return new ApiError(500, message)
          }
      
          static forbidden(message) {
              return new ApiError(403, message)
          }
      }
      

export default new ApiError();


and in another I use:
import { Request, Response, NextFunction } from "express";
import ApiError from '../errors/ApiError';

const errorHandler = function (err: ApiError, req: Request, res: Response, next: NextFunction){
    if (err instanceof ApiError) {
        return res.status(err.status).json({message: err.message});
    }
    return res.status(500).json({message: "Непредвиденная ошибка!"})
}

export default errorHandler;


And here I get:
'ApiError' refers to a value, but is being used as a type here. Did you mean 'typeof ApiError'?

4 const errorHandler = function (err: ApiError, req: Request, res: Response, next: NextFunction){
                                      ~~~~~~~~

    at createTSError (/home/ihor/Test Task by Komah Ihor/node_modules/ts-node/src/index.ts:587:12)
    at reportTSError (/home/ihor/Test Task by Komah Ihor/node_modules/ts-node/src/index.ts:591:19)
    at getOutput (/home/ihor/Test Task by Komah Ihor/node_modules/ts-node/src/index.ts:921:36)
    at Object.compile (/home/ihor/Test Task by Komah Ihor/node_modules/ts-node/src/index.ts:1189:32)
    at Module.m._compile (/home/ihor/Test Task by Komah Ihor/node_modules/ts-node/src/index.ts:1295:42)
    at Module._extensions..js (internal/modules/cjs/loader.js:1097:10)
    at Object.require.extensions.<computed> [as .ts] (/home/ihor/Test Task by Komah Ihor/node_modules/ts-node/src/index.ts:1298:12)
    at Module.load (internal/modules/cjs/loader.js:933:32)
    at Function.Module._load (internal/modules/cjs/loader.js:774:14)
    at Module.require (internal/modules/cjs/loader.js:957:19)
[nodemon] app crashed - waiting for file changes before starting...


if interrupted through a call directly, export default ApiError();it gives
/home/ihor/Test Task by Komah Ihor/node_modules/ts-node/src/index.ts:587
    return new TSError(diagnosticText, diagnosticCodes);
           ^
TSError: ⨯ Unable to compile TypeScript:
src/middlewares/ErrorHandlingMiddleware.ts:6:31 - error TS2339: Property 'status' does not exist on type 'ApiError'.

6         return res.status(err.status).json({message: err.message});
                                ~~~~~~

    at createTSError (/home/ihor/Test Task by Komah Ihor/node_modules/ts-node/src/index.ts:587:12)
    at reportTSError (/home/ihor/Test Task by Komah Ihor/node_modules/ts-node/src/index.ts:591:19)
    at getOutput (/home/ihor/Test Task by Komah Ihor/node_modules/ts-node/src/index.ts:921:36)
    at Object.compile (/home/ihor/Test Task by Komah Ihor/node_modules/ts-node/src/index.ts:1189:32)
    at Module.m._compile (/home/ihor/Test Task by Komah Ihor/node_modules/ts-node/src/index.ts:1295:42)
    at Module._extensions..js (internal/modules/cjs/loader.js:1097:10)
    at Object.require.extensions.<computed> [as .ts] (/home/ihor/Test Task by Komah Ihor/node_modules/ts-node/src/index.ts:1298:12)
    at Module.load (internal/modules/cjs/loader.js:933:32)
    at Function.Module._load (internal/modules/cjs/loader.js:774:14)
    at Module.require (internal/modules/cjs/loader.js:957:19)
[nodemon] app crashed - waiting for file changes before starting...

What to do? how to be how?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
K
komigor, 2021-07-10
@komigor

In short, here is the finished code

class ApiError extends Error {
  status: number;

  message: string;

  constructor(status: number, message: string) {
    super();
    this.status = status;
    this.message = message;
  }

  static badRequest(message: string) {
    return new ApiError(404, message);
  }

  static internal(message: string) {
    return new ApiError(500, message);
  }

  static forbidden(message: string) {
    return new ApiError(403, message);
  }
}

export default ApiError;

And here is the handler:
/* eslint-disable @typescript-eslint/no-unused-vars */
import { Request, Response, NextFunction } from 'express';
import ApiError from '../errors/ApiError';

const errorHandler = function (
  err: ApiError,
  req: Request,
  res: Response,
  next: NextFunction,
): Response {
  if (err instanceof ApiError) {
    return res.status(err.status).json({ message: err.message });
  }
  return res.status(500).json({ message: 'Непредвиденная ошибка!' });
};

export default errorHandler;

A
Alex, 2021-07-10
@Kozack

First, read the error, everything is said there:

'ApiError' refers to a value, but is being used as a type here. Did you mean 'typeof ApiError'?

Second, don't confuse TYPE and object instance. The error is precisely from the fact that you are using a variable as a type. In your case, you must export both the instance and the class itself. And use the class as a type.
class ApiError extends Error {}

const apiErrorInstance = new ApiError

const someFn1 = (err: ApiError) => {}

// @ts-expect-error
const someFn2 = (err: apiErrorInstance) => {}

playground

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question