Doing cast with number does not change the data type

2

I am learning javascript and Angular, Because at the moment of seeing the data type of this variable even specifying the data type it still comes out as string being a number

this.activatedRoute.params.subscribe( params => {
  const idx: number = (<number>params['id']);
  console.log('por que string??? ' + typeof idx);
  this.category = this._categoryService.getCategory( idx );
});

    
asked by A. Monsalve 05.09.2018 в 18:38
source

1 answer

2

Try using the parseInt() method to convert from string to number :

  const idx: number = parseInt(params['id']);
  console.log('por que string??? ' + typeof idx);
  this.category = this._categoryService.getCategory( idx );

A <Type> is called Type Assertation . According to the documentation:

  

Type assertions are a way of telling the compiler "believe me,   I know what I'm doing. "A type assertion is like a type of   conversion in other languages, but does not perform any verification   special or data restructuring. It has no impact on time of   execution, and the compiler uses it exclusively. TypeScript assumes that   you, the programmer, have made the special controls that   you need

Which means that you do not necessarily cast it, but only provide more information about the type to cast.

    
answered by 05.09.2018 / 18:47
source