Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

122
Views
Typescript narrowing in not working with Cookies.get function

I'm using js-cookie alongside with typescript and I'm getting stuck with types while trying to parse a cookie item:

// the item 'number' contains a javascript number (ex:5)
let n:number 
if(typeof Cookies.get('number')!== 'undefined'){
    n = JSON.parse(Cookies.get('number'))
}else{
    n = 0
}

Typescript: Argument of type 'string | undefined' is not assignable to parameter of type 'string'. Type 'undefined' is not assignable to type 'string'

I'm following the basic example of typescript documentation: https://www.typescriptlang.org/docs/handbook/2/narrowing.html

Am I making something wrong with this code snippet ?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You have two calls of Cookies.get('number'). Typescript can not know that the same value is returned for both calls.

Therefore, save the value in a variable:

let n:number 
let value = Cookies.get('number')
if(typeof value !== 'undefined'){
    n = JSON.parse(value)
}else{
    n = 0
}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!