Using type values in TypeScript

I am trying to assign interfaces as values within a config object:

export interface RouterConfig {
  startEvents?: typeof RouterEvent[];
  completeEvents?: typeof RouterEvent[];
}

The intended usage is as follows:

private config: RouterConfig = {
  startEvents: [NavigationStart],
  completeEvents: [NavigationEnd, NavigationCancel, NavigationError]
};

However, this approach is resulting in an error message:

The types of the 'completeEvents' property are incompatible. The type '(typeof NavigationEnd | typeof NavigationCancel | typeof NavigationError)[]' cannot be assigned to type 'RouterEvent[]'. The type 'typeof NavigationEnd | typeof NavigationCancel | typeof NavigationError' cannot be assigned to type 'RouterEvent'. The type 'typeof NavigationEnd' cannot be assigned to type 'RouterEvent'. The 'id' property is missing in the 'typeof NavigationEnd' type.

Any suggestions on how to resolve this issue?

You can find a reproduction of this issue on StackBlitz

Please note that RouterEvent refers to a class

Answer №1

When working with classes like NavigationEnd, NavigationCancel, and NavigationError, it's important to note that they have constructors with arguments. On the other hand, the RouterEvent type has a constructor without arguments. This is why the assignment may fail if not handled correctly.

If you wish to take in a constructor with any number of arguments, you should use a constructor signature that reflects this requirement. For example, using

new (...args: any[]) => RouterEvent
would work in such cases. Angular conveniently provides a type alias for this kind of constructor in the form of the Type type, making it easier for us to implement:

import { Component, Type } from '@angular/core';
import { RouterEvent, NavigationStart, NavigationEnd, NavigationCancel, NavigationError } from '@angular/router';

export interface RouterConfig {
  startEvents?: Type<RouterEvent>[];
  completeEvents?: Type<RouterEvent>[];
}
let config: RouterConfig = {
  startEvents: [NavigationStart],
  completeEvents: [NavigationEnd, NavigationCancel, NavigationError]
};

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

Steps for sending an image to Cloudinary using the fetch API

Struggling to figure out how to successfully upload a file to Cloudinary using fetch on my front-end. After consulting the documentation and various StackOverflow threads, I'm still facing a frustrating 400 error: export async function uploadImageToCl ...

When attempting to send file data in a $http Post request in Angular 8, the Rails API logs show an empty object {}

Using Angular 8 with a Rails 5.2 API I am currently attempting to add an image attachment feature to my Event model in the edit form. I have been following instructions from this specific tutorial Below is a snippet of my TypeScript code: const httpOpti ...

What are the appropriate Typescript typings for React Components that have the ability to return a string or their child components directly?

What are the suitable types for a React Component that can also output a string or directly its children, in addition to a JSX.Element? For example: type PropsStringExample = Readonly<{ returnString: boolean; }>; type PropsChildrenExample = Readon ...

What is the best way to pass a string value instead of an event in Multiselect Material UI?

Greetings, currently utilizing Material UI multi select within a React TypeScript setup. In order to modify the multi select value in the child component, I am passing an event from the parent component. Here is the code for the parent component - import ...

Encountering a Vueify Typescript error in a Vue project

Recently diving into the world of Vue, I was able to successfully create a sample app using gulp, vueify, and TypeScript. To showcase what's happening and shed light on an issue I'm facing, here are snippets of the key code segments: Menu.ts im ...

Attempting to utilize pdf.js may result in an error specifying that pdf.getPage is not a recognized function

After installing pdfjs-dist, I attempted to extract all text from a specific PDF file using Node and pdfjs. Here is the code I used: import pdfjs from 'pdfjs-dist/build/pdf.js'; import pdfjsWorker from 'pdfjs-dist/build/pdf.worker.entry.js&a ...

Incorporate OpenLayers 4 into your Angular 5 application

I'd like to integrate OpenLayers 4 into Angular 5 for a project. My main goal is to implement the QuickStart example provided on the official OpenLayers Site. This is what I have accomplished so far: npm install ol --save to download the OpenLayer ...

What is the best way to trigger a function when a button is enabled in Angular 8?

Here is a portion of my sign-in.component.html file. I have created a function in the corresponding sign-in.component.ts file that I want to trigger when the button below becomes enabled. Here is an example of what I am trying to achieve: <div class= ...

Implementing the breadcrumb component within dynamically loaded modules loaded through the router-outlet component

I'm currently working on an angular 8 breadcrumb component for my application. The requirement is to display it in the content of the page, not just in the header, and it should never be located outside the router-outlet. This has posed a challenge fo ...

What is the best way to retrieve the file path of a imported Angular module?

I am trying to figure out how to retrieve the path of the BarComponent within the code snippet below. Specifically, I need to obtain '../bar/bar.component'. When dealing with a module loaded from a package such as Component module, I would like t ...

Is there a more efficient method for invoking `emit` in Vue's Composition API from an external file?

Is there a more efficient way to access the emit function in a separate logic file? This is my current approach that is functioning well: foo.js export default (emit) => { const foo = () => { emit('bar') }; return { foo }; } When ...

Component in Next.js fetching data from an external API

I am attempting to generate cards dynamically with content fetched from an API. Unfortunately, I have been unsuccessful in finding a method that works during website rendering. My goal is to pass the "packages" as properties to the component within the div ...

Is there a way to set up a background process within electron that captures a screenshot of the entire desktop?

I'm currently working on a Desktop application using Angular2 and Electron that captures screenshots of the entire desktop and saves them to a specified path on my PC. The code for capturing screenshots is implemented in the app.component.ts file, but ...

Developing React component libraries with TypeScript compared to Babel compiler

Currently, I'm utilizing the babel compiler for compiling my React component libraries. The initial choice was influenced by Create React App's use of the same compiler. However, I've encountered challenges with using babel for creating libr ...

Is it possible for a Firestore query using .where() to conduct a search with no results?

Currently, I am in the process of creating a platform where users can upload past exams. Each document contains various fields such as teacher, year, and class, all stored in cloud Firestore. To filter the data by teacher, I am using the .where("Teacher" ...

Are there any methods within Angular 2 to perform Angular binding within a string?

When creating an HTML template with routing, such as shown below: <ul class="sb-sub-menu"> <li> <a [routerLink]="['clientadd']">Client Add</a> </li> </ul> It functions as expected. However, w ...

Creating an object property conditionally in a single line: A quick guide

Is there a more efficient way to conditionally create a property on an object without having to repeat the process for every different property? I want to ensure that the property does not exist at all if it has no value, rather than just being null. Thi ...

Reimbursement for utilizing SwitchMap in Rxjs within the Angular framework

I'm new to using switchMap for the first time and I am encountering an issue. The console is asking me to return a value, but whenever I try to do so, it doesn't seem to be working properly. @Effect() subData$ = this.actions$.pipe( ofType( ...

Using Jest and TypeScript to mock the return value of react-oidc-context

For our project, we utilize react-oidc-context to handle user authentication using oidc-client-ts under the hood. The useAuth function provided by react-oidc-context gives us access to important information such as isAuthenticated, isLoading, and the auth ...

Utilize a vacant implementation of an interface

I have a simple interface called EmployerContact. I'm wondering how I can create an empty object, mockEmployerContact, of type EmployerContact and then assign values to its properties later on. Do I need to start with default values for this object? e ...