Home > Software engineering >  Possible to save type in object?
Possible to save type in object?

Time:08-16

The below example gives the correct calculation, but for some reason p.calcPrice is a string. I would expect that it is a number, as .toFixed() doesn't make sense in a string.

Whenever I use p.calcPrice, do I then have to cast it with p.calcPrice, or can I have TypeScript treat as a number, so I don't have to cast it?

p.calcPrice = (
  price *
   p.amount *
  (1 - pD / 100) *
  (1 - mD / 100)
).toFixed(2);

CodePudding user response:

toFixed returns a string, you have to cast it manually.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed#return_value

one way for casting would be to wrap it in Number:

p.calcPrice = Number((price *  p.amount * (1 - pD / 100) * (1 - mD / 100)).toFixed(2));

CodePudding user response:

You could rewrite it like this so it will already be cast to a number because toFixed returns a string. Mind the before the clause.:

p.calcPrice =  (
  price *
   p.amount *
  (1 - pD / 100) *
  (1 - mD / 100)
).toFixed(2);
  • Related