When the nestjs interface appears to be missing a defined method

Upon reviewing the code at this link:

https://github.com/nestjs/nest/tree/master/packages/common

One can see that the interface ArgumentsHost has been defined, but the contents of its methods are not explicitly defined.

However, when looking at the following code snippet:

https://docs.nestjs.com/exception-filters

It is evident that ArgumentsHost is used and the method switchToHttp() functions correctly.

How is it that these methods work without having specific definitions? Is there a key point that I am missing as a beginner in this context? Any insights or opinions would be greatly appreciated.

Thank you.

import { ExceptionFilter, Catch, ArgumentsHost, HttpException } from '@nestjs/common';
import { Request, Response } from 'express';

@Catch(HttpException)
export class HttpExceptionFilter implements ExceptionFilter {
  catch(exception: HttpException, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse<Response>();
    const request = ctx.getRequest<Request>();
    const status = exception.getStatus();

    response
      .status(status)
      .json({
        statusCode: status,
        timestamp: new Date().toISOString(),
        path: request.url,
      });
  }
}

Answer №1

This concept is not exclusive to Nest but rather applies to TypeScript (and other languages) in a broader sense. When you define an interface, you are essentially specifying a type, and when your catch method requires a second argument, it must adhere to that type. In simple terms, any value with the correct structure can be utilized as the second argument.

In the case of Nest library, it is responsible for providing a specific value to your defined catch method, ensuring it conforms to the ArgumentsHost interface. For instance, you can refer to the implementation of ExecutionContextHost as an example of such an instance.

This approach is a versatile and powerful way to create functions that only require inputs with a particular structure, such as specific properties or methods.

For instance, consider a graphics library with a render function that accepts an array of shape objects to draw on the screen. The shapes can vary greatly, like squares, circles, or even unique shapes, as long as they have the necessary drawing method:

function render(shapes: Drawable[]) {
  shapes.forEach(shape => shape.draw());
}

interface Drawable {
  draw: () => void;
}

Hence, any object with a compatible draw method can be included in the array of arguments for render, regardless of its other properties.

In conclusion, the draw method is not explicitly dictated by the Drawable interface; rather, the interface acts as a filter, allowing only certain elements to pass through.

The draw method is implemented by concrete instances of the interface, such as:

class Square extends Drawable {
  public x: number;
  public y: number;
  public sideLength: number;

  draw() {
    // Drawing logic here
  }
}

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

Retrieve the raw text from the input field instead of the date object

Below is the HTML code for an input field: <div class="input-group input-group-md"> <input id="date" name="date" [readOnly]="disabled" type="text" placeholder="M0/d0/0000 Hh:m0:s0" [placeholder]="pl ...

Unraveling nested elements with the array map() method in Angular2 and Typescript: Fixing the issue of undefined property reference while mapping

Hey there! I'm currently working with Angular 4 and I have a piece of code that parses data from an API into a TypeScript array of rows. It's important to note that the code functions properly if elements like 'item.tceCampRun' and &apo ...

When using TypeORM's save() method with an array of objects, the @PrimaryColumn() annotations are ignored, resulting

My current situation involves an entity called Point: @Entity() export class Point { @PrimaryGeneratedColumn('uuid') id: string; @IsUUID() @PrimaryColumn({ type: 'uuid', ...

It appears that Jest is having trouble comprehending the concept of "import type"

We've just completed a major update to our monorepository, bringing it up to date with the following versions: Nx 14.3.6 Angular 14.0.3 Jest 28.1.1 TypeScript 4.7.4 Although the compilation process went smoothly after the upgrade, we encountered num ...

Higher-Order Component integrated with HTMLElement

Check out this complex code snippet I created: export type AdvancedHoverElementProps<TElement extends HTMLElement> = React.HTMLProps<TElement> & { hoverDuration: number, onHoverChanged: (isHovering: boolean) => void }; export ...

Achieving Jest integration with Angular 9 in a Storybook setup

We are currently utilizing Storybook 5 alongside Angular 9, with Jest 26 for some of the testing procedures. The issue we're facing arises when using Typescript version below 3.8.0 - a requirement for Angular 9's ng build --prod. This results in ...

The incredible power of the MongoDB $inc field

I am facing a challenge in writing a function that accepts a record id, an action (inc or dec), and a field name as a string to be incremented (can be 'likes', 'subs' or any other). The issue is that I am unable to find a way to replac ...

Can all intervals set within NGZone be cleared?

Within my Angular2 component, I have a custom 3rd party JQuery plugin that is initialized in the OnInit event. Unfortunately, this 3rd party library uses setIntervals extensively. This poses a problem when navigating away from the view as the intervals rem ...

A specialized type that guarantees a string union includes a particular string literal

I need to define a Mapped type that specifies a field named status which can be either a string or the string value ready: This example works as expected: export type ValidServiceState = HasReady<{ status: "ready" }>; The following should ...

Can you conduct testing on Jest tests?

I am in the process of developing a tool that will evaluate various exercises, one of which involves unit-testing. In order to assess the quality of tests created by students, I need to ensure that they are effective. For example, if a student provides the ...

Having trouble moving to a different component in Angular?

In my application, I am facing an issue with navigating from List to Details component by passing the ID parameter. It seems that there is no response or error when attempting to call the relevant method. Below, you can find the code snippets related to th ...

What is the best way to sort through an Array of photo filenames?

https://i.sstatic.net/04cws.pngI have a list of image names that contain UUIDs. images [ "auditid_626_UUID_666666_time__1582577405550.jpg", "auditid_626_UUID_999999_time__1582577405554.jpg", "auditid_626_UUID_999999_time__15825 ...

Tips for effectively handling the data received from a webservice when logging into a system

My web service provides me with permissions from my user. The permissions are stored as an array in JSON format. I need to find a way to access and display this data in another function. {"StatusCode":0,"StatusMessage":"Authenticated Successfully", "Token ...

Exploring the use of a customizable decorator in Typescript for improved typing

Currently, I am in the process of creating TypeScript typings for a JavaScript library. One specific requirement is to define an optional callable decorator: @model class User {} @model() class User {} @model('User') class User {} I attempted ...

Encountering issues with compiling files in react app using webpack, failing to compile as anticipated

When it comes to compiling, I prefer using webpack with TypeScript files. In my webpack.config.js file: module.exports = async (env, options) => { const dev = options.mode === "development"; const config = { //Webpack configuration pr ...

Is there a way to exclusively view references of a method override in a JS/TS derived class without any mentions of the base class method or other overrides in VS Code?

As I work in VS Code with TypeScript files, I am faced with a challenge regarding a base class and its derived classes. The base class contains a method called create(), which is overridden in one specific derived class. I need to identify all references ...

Encountering a Node-gyp rebuild issue while integrating NGRX into an Angular application on Mac OS

I am currently working on integrating ngrx/store into my Angular application. Johns-MBP:Frontend johnbell$ npm install @ngrx/store <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="aac9cbc4dccbd9ea9b849c849b99">[email pr ...

What is the best way to utilize the `Headers` iterator within a web browser?

Currently, I am attempting to utilize the Headers iterator as per the guidelines outlined in the Iterator documentation. let done = false while ( ! done ) { let result = headers.entries() if ( result.value ) { console.log(`yaay`) } ...

The existence of useRef.current is conditional upon its scope, and it may be null in certain

I'm currently working on drawing an image on a canvas using React and Fabric.js. Check out the demo here. In the provided demo, when you click the "Draw image" button, you may notice that the image is not immediately drawn on the canvas as expected. ...

Creating dynamic components with constructor parameters in Angular 9

Having trouble passing a value to the constructor in the component generation code. Check out the original code here: https://stackblitz.com/edit/angular-ivy-tcejuo private addComponent(template: string) { class TemplateComponent { @ViewChild( ...