[英]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:我将 js-cookie 与 typescript 一起使用,并且在尝试解析 cookie 项时遇到了类型:
// 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 | Typescript : 类型参数 'string | undefined' is not assignable to parameter of type 'string'.
undefined' 不能分配给'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我正在关注 typescript 文档的基本示例: 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')
.您有两个电话
Cookies.get('number')
。 Typescript can not know that the same value is returned for both calls. Typescript 无法知道两次调用都返回了相同的值。
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
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.