1

Angular(6) Router "Params" object is declared as follows:

export declare type Params = {
    [key: string]: any;
};

Is it an error to instantiate it as follows? -

newParams = new Params();

Than add items to it as follows:

params.push({name: value});

Pycharm says I cannot initialize the way I do. Is Params a type or some kind of higher level type that needs to be treated other way?

1
  • 1
    Yes, it's an error. The TS compiler tells you as much: 'Params' only refers to a type, but is being used as a value here. Also if you want to have a push method you should really define that explicitly, not as part of a general index signature. If you want to new something up you need to define a class. Commented Jul 23, 2018 at 9:27

3 Answers 3

2

Where the Params type alias is used, it's telling you that it is (or expects) an object literal with key|value pairs, with the value being of type any

export declare type Params = {
    [key: string]: any;
};

It's not a class, so you cannot instantiate it. Officially it's called a type alias, and acts more like an interface than a class, but with some differences e.g. cannot be implemented by a class

It's not terribly helpful, as every object can have key|value pairs, but aliases are used in some cases for documentation purposes

In the ActivatedRoute documentation, we can see that the params Observable returns objects of type Params - so we know there will be values we can access using property accessor bracket notation route.snapshot.params["id"];

params  Observable<Params>  
An observable of the matrix parameters scoped to this route
Sign up to request clarification or add additional context in comments.

Comments

1
type ErrorResponse = {
  message: string;
};

const error: ErrorResponse = { message: 'Ups' };

Another alternative as explained here:

const error = <ErrorResponse>{ message: 'Ups' };

Comments

0

Guess it's more complicated than that, but the simple answer is, just initialize it with an empty object as follows:

const params: Params = {};

Took it from the Angular open source... sometimes the best way is just to dig in the sources :-)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.