'string | 类型的参数null' 不能分配给类型为 'string' 的参数 [英] Argument of type 'string | null' is not assignable to parameter of type 'string'

查看:46
本文介绍了'string | 类型的参数null' 不能分配给类型为 'string' 的参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是打字稿的初学者.我正在尝试获取我的本地存储变量 auth 值.我知道本地存储中的变量存储为字符串.所以我使用 JSON.parse 将它转换为布尔值,但我收到错误消息 [Argument of type 'string |null' 不能分配给类型为 'string' 的参数.类型 'null' 不能分配给类型 'string'].

I am very beginner in typescript. I am trying to get my local storage variable auth value. I know variable in local storage are stored as a string. So I am converting it into Boolean using JSON.parse But I am getting error saying [Argument of type 'string | null' is not assignable to parameter of type 'string'. Type 'null' is not assignable to type 'string'].

在第 2 行出现错误,我在其中声明 auth 变量

Getting error at line: 2 where I am declaring auth Variable

let leftmenu;
    const auth:boolean = JSON.parse(localStorage.getItem('auth'));
    if (auth === true) {
        leftmenu = (
            <React.Fragment>
                <Navbar.Text>
                    Signed in as: <a href="#login">Mark Otto</a>
                </Navbar.Text>
                <Button variant="outline-success">Logout</Button>
            </React.Fragment>);
    } else {
        leftmenu = (
            <React.Fragment>
                <Button variant="outline-success">Login</Button>
                <Button variant="outline-success">Sign Up</Button>
            </React.Fragment>
        )
    }

推荐答案

因为 localStorage.getItem('auth') 有可能返回 null,而 JSON.parse 需要一个字符串.

Because it's possible that localStorage.getItem('auth') will return null, while JSON.parse requires a string.

在解析变量之前,您需要进行空检查.

You will need to do a null check before parsing the variable.

cosnt authRaw: string = localStorage.getItem('auth');
if(authRaw !== null){
    const auth: boolean = JSON.parse(authRaw);
}

更简单的方法是使用 ?? 添加回退值作为 localStorage.getItem('auth')

A simpler approach is to use ?? to add a fallback value as an alternative to localStorage.getItem('auth')

const auth:boolean = JSON.parse(localStorage.getItem('auth') ?? "false");

这篇关于'string | 类型的参数null' 不能分配给类型为 'string' 的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆