Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing types as values in typescript

I want to pass interfaces as values to a config object:

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

Usage should be like:

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

But it is throwing an error:

Types of property 'completeEvents' are incompatible. Type '(typeof NavigationEnd | typeof NavigationCancel | typeof NavigationError)[]' is not assignable to type 'RouterEvent[]'. Type 'typeof NavigationEnd | typeof NavigationCancel | typeof NavigationError' is not assignable to type 'RouterEvent'. Type 'typeof NavigationEnd' is not assignable to type 'RouterEvent'. Property 'id' is missing in type 'typeof NavigationEnd'.

How can I fix it?

Here is a stackblitz reproduction

Note that RouterEvent is a class

like image 226
Murhaf Sousli Avatar asked Feb 03 '26 17:02

Murhaf Sousli


1 Answers

The classes all NavigationEnd, NavigationCancel, NavigationError have constructors with arguments. The type RouterEvent has a constructor without arguments. This is why the assignment fails. If you want to take in a constructor with any number of arguments you need to use a constructor signature that reflects that, for example this would work new (...args: any[]) => RouterEvent Angular already defines a type alias for this contructor in the form of the Type type. So we can write it like this:

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]
};
like image 140
Titian Cernicova-Dragomir Avatar answered Feb 06 '26 07:02

Titian Cernicova-Dragomir



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!