简体   繁体   中英

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?

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM