'string | 类型的参数 null' 不能分配给类型为 'string' 的参数

IT技术 reactjs typescript
2021-05-16 22:29:46

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

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

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>
        )
    }
2个回答

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

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

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

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

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

尝试这样的事情:

const auth: string | null = JSON.parse(localStorage.getItem('auth'));
if (auth!== null) {
    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>
    )
}
}