Jim*_*ode 30 local-storage typescript reactjs
我有以下代码行:
const allGarments = teeMeasuresAverages || JSON.parse(localStorage.getItem("teeMeasuresAverages")) || teeMeasuresAveragesLocal;
Run Code Online (Sandbox Code Playgroud)
Typescript 抛出此警告:
Argument of type 'string | null' is not assignable to parameter of type 'string'.
Type 'null' is not assignable to type 'string'.
Run Code Online (Sandbox Code Playgroud)
所以我尝试包含非空断言运算符(!):
Argument of type 'string | null' is not assignable to parameter of type 'string'.
Type 'null' is not assignable to type 'string'.
Run Code Online (Sandbox Code Playgroud)
然后这给了我一个不同的警告:
Forbidden non-null assertion.
Run Code Online (Sandbox Code Playgroud)
我是打字稿新手。它在这里寻找什么?
Yah*_*var 58
依赖类型JSON.parse必须是string.
但local storage返回类型是string|null这样的,所以它可以是两者string,null并且当您声明数据时,其值为空,直到您渲染组件(或调用函数)然后调用getItem,它获取值,然后它是一个string.
您可以使用||运算符并向其中添加一个字符串,使其不再为空。
JSON.parse(localStorage.getItem("teeMeasuresAverages") || '""')
Run Code Online (Sandbox Code Playgroud)
您还可以添加// @ts-ignore以防止 TypeScript 检查下一行中的类型,但不建议这样做
// @ts-ignore
JSON.parse(localStorage.getItem("teeMeasuresAverages"))//just the usual way
Run Code Online (Sandbox Code Playgroud)
cap*_*ian 12
JSON.parse期望string作为第一个参数
JSON.parse(text: string, reviver?: ((this: any, key: string, value: any) => any) | undefined): any
Run Code Online (Sandbox Code Playgroud)
localStorage返回时string | null。
const value = localStorage.getItem("teeMeasuresAverages") // string | null
Run Code Online (Sandbox Code Playgroud)
如果你想让TS开心就检查一下是否value是一个stirng
const value = localStorage.getItem("teeMeasuresAverages")
if (typeof value === 'string') {
const parse = JSON.parse(value) // ok
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
58975 次 |
| 最近记录: |