Reputation: 13286
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
Upvotes: 3
Views: 2137
Reputation: 249466
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]
};
Upvotes: 4