我有以下代码行:
const allGarments = teeMeasuresAverages || JSON.parse(localStorage.getItem("teeMeasuresAverages")) || teeMeasuresAveragesLocal;
Typescript 抛出此警告:
Argument of type 'string | null' is not assignable to parameter of type 'string'.
Type 'null' is not assignable to type 'string'.
所以我尝试包含非空断言运算符 (!):
const allGarments = teeMeasuresAverages || JSON.parse(localStorage.getItem("teeMeasuresAverages")) || teeMeasuresAveragesLocal;
然后给了我一个不同的警告:
Forbidden non-null assertion.
我是打字稿的新手。它在这里寻找什么?
答案 0 :(得分:3)
JSON.parse
依赖项的类型必须是 string
但是 local storage
返回类型是 string|null
所以它可以是 string
和 null
并且当你声明数据时,它的值是空的,直到你呈现组件(或调用函数)然后调用 getItem
函数,它获取值,然后它是一个 string
。
您可以使用 ||
操作并为其添加一个字符串,使其不再为空。
JSON.parse(localStorage.getItem("teeMeasuresAverages") || "")
也可以添加// @ts-ignore
来防止type script检查下一行的类型,但不推荐
// @ts-ignore
JSON.parse(localStorage.getItem("teeMeasuresAverages"))//just the usual way
答案 1 :(得分:3)
JSON.parse
期望 string
作为第一个参数
JSON.parse(text: string, reviver?: ((this: any, key: string, value: any) => any) | undefined): any
当 localStorage
返回 string | null
时。
const value = localStorage.getItem("teeMeasuresAverages") // string | null
如果您想让 TS 开心,只需检查 value
是否令人兴奋
const value = localStorage.getItem("teeMeasuresAverages")
if (typeof value === 'string') {
const parse = JSON.parse(value) // ok
}