1

I have this typescript code:

categoryColumnWide: number = 0;

this.categoryColumnWide = parseInt(storage.getItem('categoryColumnWide') || 1);

Giving me the following error:

Severity Code Description Project File Line Suppression State Error Build:Argument of type 'string | 1' is not assignable to parameter of type 'string'.

Can someone help me with this? I just upgraded to a new version of Typescript and this message is appearing now in multiple places. When I hover over categoryColumnWide it says it's a "number"

FYI As far as I know I am using Typescript 2.1

Alan2
  • 23,493
  • 79
  • 256
  • 450
  • 2
    if `storage.getItem('categoryColumnWide')` return a falsy value then `1` will be chosen and passed as parametter to `parseInt` and since `parseInt` expects a `string`, it says that you can not assign a number to a string! – ibrahim mahrir Apr 05 '17 at 11:13
  • 1
    Changing it to `parseInt(storage.getItem(...) || "1")` or `Number((storage.getItem(...) || 1))` will solve the problem! – ibrahim mahrir Apr 05 '17 at 11:15
  • Or you can check if the item is in the storage before start using it like: `if(storage.getItem('categoryColumnWide')) { storage.setItem('categoryColumnWide', '1'); }`! – ibrahim mahrir Apr 05 '17 at 11:18
  • 1
    or just `parseInt(storage.getItem('categoryColumnWide')) || 1` – Aleksey L. Apr 05 '17 at 11:19
  • 1
    @AlekseyL. what if `storage.getItem('categoryColumnWide')` returned `"0"`? – ibrahim mahrir Apr 05 '17 at 11:20
  • Possible solutions: [**Here**](http://stackoverflow.com/questions/39475166/typescript-error-when-using-parseint-on-a-number) and [**Here**](http://stackoverflow.com/questions/14667713/typescript-converting-a-string-to-a-number)! – ibrahim mahrir Apr 05 '17 at 11:24
  • @ibrahimmahrir you are right - it can cause not desired behavior – Aleksey L. Apr 05 '17 at 11:25
  • ... and [**Here**](http://stackoverflow.com/questions/23437476/in-typescript-how-to-check-if-a-string-is-numeric)! – ibrahim mahrir Apr 05 '17 at 11:30

1 Answers1

0

parseInt requires string argument

your code passes storage.getItem('categoryColumnWide') (string) or 1 (number)

try passing 1 as string

this.categoryColumnWide = parseInt(storage.getItem('categoryColumnWide') || '1');
mleko
  • 11,650
  • 6
  • 50
  • 71