Steps for verifying if an instance conforms to an interface

When working with PHP, we can check for a specific instance like this. Check it out here

interface IInterface
{
}

class TheClass implements IInterface
{
}

$cls = new TheClass();
if ($cls instanceof IInterface) {
    echo "yes";
}

I have a similar scenario in Typescript and I'm checking it like so.

public handle() {

        return (err: any, req: Request, res: Response, next: any) => {

            switch (err.constructor) {

                case MyException:
                    var response = err.getResponse();
                    res.status(500).send(response);
                    break;
                default:
                    res.status(500).send(err.message);

            }
        }
 }

Instead of using MyException, now I want to check against IMyException. Any suggestions on how I can achieve this?

Answer №1

Runtime behavior does not involve interfaces. TypeScript interfaces strictly ensure structural compatibility. An instance of a class that is expected to adhere to a specific type (e.g. err: MyException) does not necessarily have to be an identical instance of the class with the same name.

In order for an interface to play a role at runtime, it must take the form of a class. If a particular class is not meant to be instantiated directly, it should be abstract, and a concrete class should inherit from it:

abstract class BaseMyException {
  ...
}

class MyException extends BaseMyException {}

This way, it can be validated as an instance of this class using err instanceof BaseMyException. It's important to note that err.constructor only checks its own constructor.

Answer №2

In TypeScript, it is not possible to achieve this as interfaces are limited to compile time.

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

In TypeScript, the first element of an array can be inferred based on the second element

Let's consider a scenario where we have a variable arr, which can be of type [number, 'number'] or [null, 'null']. Can we determine the type of arr[0] based on the value of arr[1]? The challenge here is that traditional function ov ...

Creating a list with axios in the ngOnInit lifecycle hook

I have a feature where I need to populate objects fetched from the backend. ngOnInit() { this.source.load(this.myService.findAll()); } Within myService, I am using Axios to retrieve data from the backend. I can confirm that the data is success ...

A guide on leveraging Observable forkJoin with TransferObject in Ionic 3 and Angular 4

Using Express server and Multer for file handling. An array object named uploadArr holds the following data: var url = "http://192.168.8.101:3000/store_points_upload"; let targetPaths = []; let filenames = []; let optionLists = []; this.di ...

express-namespace and express-resource do not support mapping

I'm currently working on creating a customized map for a specific resource. app.namespace('/v1', function(){ var sessionResource = app.resource('session', require('./routes/v1/session')); sessionResource.map('/t ...

NextJS is throwing an error when trying to use a .mdx file with Typescript

Everything is working fine for rendering components on the website, but TypeScript is showing an error when importing mdx files. The TypeScript error message reads: Cannot find module '@/articles/good.mdx' or its corresponding type declarations. ...

Universal Enum variable

I came up with a function that accepts a specific type of enum value to determine a color to pass as a prop to another function. However, I want the flexibility to throw a different enum at my function. I thought about using a generic type, but TypeScript ...

Issue [ERR_PACKAGE_PATH_NOT_EXPORTED]: Missing "exports" declaration - Firebase

Currently following a Full Stack React & Firebase Tutorial and attempting to implement Firebase Authentication for creating a new user. However, I encountered the following error: Error [ERR_PACKAGE_PATH_NOT_EXPORTED]: No "exports" main defin ...

Expressions without a call signature cannot be invoked

When using an adapter in the given example, I encountered a type error specifically on the last line of the getGloryOfAnimal method. Despite having clearly defined types, I am puzzled by this issue. interface ICheetah { pace: string; } interface ILio ...

Is it ever acceptable for Oauth 2 (Passport.js) login to fail?

When a user attempts to log in with their Google Oauth 2 account on my site for the first time using Passport.js/Express, the process unfolds as follows: OPTION 1: New User User -> clicks Google Oauth 2 login -> Backend tasks executed -> U ...

This request to access Twitter_OAuth_Url was denied as it was redirected from 'http://localhost:3000/api/twitter-login' and the origin is set to 'null'

In my MEAN STACK App, I am utilizing the passport-twitter module. One of the endpoints in my Angular app is the twitter-login, which triggers the authentication process using passport-twitter. Upon receiving the oaut_token, the user is redirected to the fo ...

An error occurs with the HTTP POST request if emojis are included in the body

Currently, I have implemented an HTTP POST method to capture user input from a uiTextField in my app. The entered text is stored as an NSString and then added to a NSDictionary. Subsequently, it undergoes conversion to JSON format and further to NSData wit ...

Leveraging both the value from getStaticProps and the parameter in the component within NextJS

With this code snippet, I am attempting to load markdown files from a specific directory and pass them to a component that will display one of the markdown files based on a specified parameter. However, I am encountering an error when trying to use the com ...

Peeling off the layers of an array declared as const to reveal its mutable version without being restricted to tuples

I'm facing a challenge with an array declared as as const: // example of a simple mock class class Child { _ = "" } const child = new Child(); const schema = [[child], child] as const; // readonly [readonly [Child], Child]; This array rep ...

Is there a way to implement imports based on a specific condition?

I'm just starting to learn Angular and TypeScript. My goal is to redirect multiple hostnames to a single Angular 6 project because most aspects are the same, with only language and URLs varying. For example, here's what I have implemented in ap ...

Exploring the intersection of React, TypeScript, and the useCallback

Struggling with Typescript and useCallback, encountered an issue Received 1 argument when expecting 0 This is the snippet of code causing trouble const searchFriends = useCallback(() => (filterValue: string): void => { if (dataState.length &l ...

Troubleshooting: Vue 3 Vite encountering 404 error when attempting to load fonts from assets using Font Loading API

Attempting to dynamically load fonts from the assets directory within Vue 3 (Typescript) using Vite has led to a 404 error occurring. https://i.sstatic.net/H3Ho7.png const fonts = import.meta.glob('@/assets/fonts/*.otf') console.log(fonts) asy ...

No data being displayed or returned from API when using async await

My Ionic 6 + Angular 14 application is currently facing an issue with displaying data retrieved from an API... I have implemented a service to fetch the data from the API and then called this service in the component. The app compiles without any errors a ...

Pause and anticipate the subscription within the corresponding function

Is there a way to make an If-Else branch wait for all REST calls to finish, even if the Else side has no REST calls? Let's take a look at this scenario: createNewList(oldList: any[]) { const newList = []; oldList.forEach(element => { if (eleme ...

What could be causing the `express` executable to malfunction in my command prompt?

After installing Node.js, I made a new folder on my C:\ drive and then proceeded to install an Express skeleton using the command: npx express-generator My intention was to check the express options by running express -h, however, I encountered the f ...

Sharing variables between files in Node.js

Just starting out in the world of web development, I am completely new to node.js. My goal is to create a website that updates an api using the chef-node client via express, with the help of this chef-node api client and this tutorial When I run a stand- ...