Returns 本地存储对象的键和值
Returns key and value of a localstorage object
我得到一个这样构建的本地存储:
TYPE_MAPPING : {"type":{"B2B":"B2B","UNKNOWN":"B2C","blabla":"B2C"}}
当我想从本地存储中检索键和值时
const type = localStorage.getItem(TYPE_MAPPING);
for (const [key, value] of Object.entries(type)) {
console.log(`${key}: ${value}`);
}
我收到以下错误消息:
TS2769: No overload matches this call.
Overload 1 of 2, '(o: { [s: string]: string; } | ArrayLike<string>): [string, string][]', gave the following error.
Argument of type 'string | null' is not assignable to parameter of type '{ [s: string]: string; } | ArrayLike<string>'.
Type 'null' is not assignable to type '{ [s: string]: string; } | ArrayLike<string>'. Overload 2 of 2, '(o: {}): [string, any][]', gave the following error.
Argument of type 'string | null' is not assignable to parameter of type '{}'. Type 'null' is not assignable to type '{}'.
恢复 localStorage 的键和值的解决方案是什么?
您要获取的类型对象嵌套在类型变量中。试试这个:
const type = localStorage.getItem(TYPE_MAPPING);
for (const [key, value] of Object.entries(type.type)) {
console.log(`${key}: ${value}`);
}
**localstorage.getItem** return a string, so you have to parse it before
const type = JSON.parse(localStorage.getItem(TYPE_MAPPING));
for (const [key, value] of Object.entries(type)) {
console.log(`${key}: ${value}`);
}
我得到一个这样构建的本地存储:
TYPE_MAPPING : {"type":{"B2B":"B2B","UNKNOWN":"B2C","blabla":"B2C"}}
当我想从本地存储中检索键和值时
const type = localStorage.getItem(TYPE_MAPPING);
for (const [key, value] of Object.entries(type)) {
console.log(`${key}: ${value}`);
}
我收到以下错误消息:
TS2769: No overload matches this call.
Overload 1 of 2, '(o: { [s: string]: string; } | ArrayLike<string>): [string, string][]', gave the following error.
Argument of type 'string | null' is not assignable to parameter of type '{ [s: string]: string; } | ArrayLike<string>'.
Type 'null' is not assignable to type '{ [s: string]: string; } | ArrayLike<string>'. Overload 2 of 2, '(o: {}): [string, any][]', gave the following error.
Argument of type 'string | null' is not assignable to parameter of type '{}'. Type 'null' is not assignable to type '{}'.
恢复 localStorage 的键和值的解决方案是什么?
您要获取的类型对象嵌套在类型变量中。试试这个:
const type = localStorage.getItem(TYPE_MAPPING);
for (const [key, value] of Object.entries(type.type)) {
console.log(`${key}: ${value}`);
}
**localstorage.getItem** return a string, so you have to parse it before
const type = JSON.parse(localStorage.getItem(TYPE_MAPPING));
for (const [key, value] of Object.entries(type)) {
console.log(`${key}: ${value}`);
}