Home > database >  Angular/TS function param typeof
Angular/TS function param typeof

Time:08-20

I have a simple function with typed param. When I check the type of param, I get "string" . How is it possible? Is it not strict-type and has to be 'number'?

Called from:

    this.serverId = this.activatedRoute.snapshot.params['id'];
    this.server = this.serversService.getServer(this.serverId);

The function:

getServer(id: number): ServerModel  {
    console.log('param type: '   typeof(id));
....
}

Console log:

param type: string

CodePudding user response:

The url param wont return you anything more than a string, it doesnt matter what your function param type is, it wont cast the actual value.

If you want to cast it as a number, you can do something like that:

this.serversService.getServer(parseInt(this.serverId, 10));

or you can use the Number constructor:

this.serversService.getServer(Number(this.serverId));

CodePudding user response:

Typescript is a preprocessor, it does not exist at runtime. It can't stop you from passing a string to that function during runtime.

The reason you don't see an error during compilation is because params has the following type:

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

As you can see params['id'] gets assigned type any. In other words the compiler has no idea what type it is, so it can't help you. It will let you assign this value to any other type.

Only you know that the return value is actually a string, so it's up to you to handle it. If you want the compiler's help, you can put the value in a temporary variable.

serverId: number;

someFn(){
  const idString: string = this.activatedRoute.snapshot.params['id'];
  this.serverId = idString; // error: string not assignable to type number
  this.server = this.serversService.getServer(this.serverId);
} 

Which lets you know you need to parse the string

serverId: number;

someFn(){
  const idString: string = this.activatedRoute.snapshot.params['id'];
  this.serverId = Number(idString);
  this.server = this.serversService.getServer(this.serverId);
} 

But, obviously it's simpler to just convert it immediately

  this.serverId = Number(this.activatedRoute.snapshot.params['id']);
  this.server = this.serversService.getServer(this.serverId);
  • Related