【问题标题】:Argument of type 'string | null' is not assignable to parameter of type 'string''string | 类型的参数null' 不能分配给“字符串”类型的参数
【发布时间】:2021-09-22 05:46:00
【问题描述】:

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

【问题讨论】:

标签: reactjs typescript


【解决方案1】:

因为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");

【讨论】:

  • 可能但并不总是返回 null。如果里面有值,那么就不会有空值
  • 是的,这就是它有string | null类型的原因,这表示它可以是它们中的任何一个。
  • TypeScript 强制你保证JSON.parse 得到一个string,这样JSON.parse 中发生的一切都会按预期工作。
  • else 条件也被定义,如果我从 localstorage 获得 null 然后 else 部分将运行。那么,为什么它会抛出错误?请用简单的方式解释
  • 我对我的条件的期望是如果auth 变量为真,则运行如果部分。如果 auth 而不是 true 中有任何可用的内容,则运行 else 部分
【解决方案2】:

试试这样的:

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>
    )
}
}

【讨论】:

  • 我对我的条件的期望是如果auth 变量为真,则运行如果部分。如果auth 中还有其他内容而不是true,则运行 else 部分。那么,我的情况有什么问题?
  • 你的条件没问题,但是你需要确保localStorage项'auth'不能为空。在您的情况下,它的价值为空。这就是为什么我添加字符串 | null 因为,假设 Parse 为 null,至少你有办法处理它
猜你喜欢
  • 2018-04-05
  • 2021-09-30
  • 2021-09-06
  • 1970-01-01
  • 1970-01-01
  • 2021-08-18
  • 1970-01-01
  • 1970-01-01
  • 2021-07-14
相关资源
最近更新 更多