从本地存储解析后类型断言不起作用
Type assertion is not working after parsing from local storage
在我的 angular 项目中,我在本地存储中存储了一组数据点。
对于数据,我创建了一个 class,如下所示:
export class Datapoint {
id: number;
name: string;
// ... some more properties.
constructor(){
}
public getDescription() {
// ... logic
}
// ... more functions
}
现在我从本地存储中检索数组并将其从字符串中解析回来。
const dpList = JSON.parse(localStorage.getItem('datapoints'));
因为 'dpList' 的类型是 'Object' 我对我的类型 'Datapoint' 做了一个类型断言。
const datapoints: Datapoint[] = [];
public someFunction(): Datapoint[] {
// Get the stringified objects from the local storage.
const dpList = JSON.parse(localStorage.getItem('datapoints'));
// Iterate through the array and push to this.datapoints.
dpList.forEach(dp => {
const asserted_dp: Datapoint = (dp as Datapoint);
this.datapoints.push(asserted_dp);
});
}
但是 asserted_dp 是在对象类型的类型断言之后,而不是我预期的数据点。所以我无法访问 Datapoint 类型的函数,因为 proto 属性 没有关于它们的信息。
如何让类型断言起作用?
提前致谢!
了解问题
本地存储只存储字符串。虽然您可能已经将数据点对象字符串化以进行存储,但是当您 JSON.parse
字符串时,它不会 return Datapoint
的实例,而是给您一个正常的 javascript Object
类型。这很重要,因为您的对象不再具有 Datapoint
方法,例如 getDescription
,因此您不能只转换类型。
可能的解决方案
我建议创建一个加载程序,从序列化字符串中重建 Datapoint
的实例。我不知道你通常是如何构建数据点的,但我会在这里举一个简单的例子
function loadDatapoints(): Datapoint[] {
var dp_objects: any = JSON.parse(localStorage.getItem('datapoints'));
var points: Datapoint[] = [];
for (var i: number = 0; i < dp_objects.length; i++) {
var point: Datapoint = new Datapoint();
// However you normally construct Datapoints...
points.push(point);
}
return points;
}
通过这种方式,您实际上是在使用 Datapoint 实例,因此类型断言现在可以按预期工作。
在我的 angular 项目中,我在本地存储中存储了一组数据点。
对于数据,我创建了一个 class,如下所示:
export class Datapoint {
id: number;
name: string;
// ... some more properties.
constructor(){
}
public getDescription() {
// ... logic
}
// ... more functions
}
现在我从本地存储中检索数组并将其从字符串中解析回来。
const dpList = JSON.parse(localStorage.getItem('datapoints'));
因为 'dpList' 的类型是 'Object' 我对我的类型 'Datapoint' 做了一个类型断言。
const datapoints: Datapoint[] = [];
public someFunction(): Datapoint[] {
// Get the stringified objects from the local storage.
const dpList = JSON.parse(localStorage.getItem('datapoints'));
// Iterate through the array and push to this.datapoints.
dpList.forEach(dp => {
const asserted_dp: Datapoint = (dp as Datapoint);
this.datapoints.push(asserted_dp);
});
}
但是 asserted_dp 是在对象类型的类型断言之后,而不是我预期的数据点。所以我无法访问 Datapoint 类型的函数,因为 proto 属性 没有关于它们的信息。
如何让类型断言起作用?
提前致谢!
了解问题
本地存储只存储字符串。虽然您可能已经将数据点对象字符串化以进行存储,但是当您 JSON.parse
字符串时,它不会 return Datapoint
的实例,而是给您一个正常的 javascript Object
类型。这很重要,因为您的对象不再具有 Datapoint
方法,例如 getDescription
,因此您不能只转换类型。
可能的解决方案
我建议创建一个加载程序,从序列化字符串中重建 Datapoint
的实例。我不知道你通常是如何构建数据点的,但我会在这里举一个简单的例子
function loadDatapoints(): Datapoint[] {
var dp_objects: any = JSON.parse(localStorage.getItem('datapoints'));
var points: Datapoint[] = [];
for (var i: number = 0; i < dp_objects.length; i++) {
var point: Datapoint = new Datapoint();
// However you normally construct Datapoints...
points.push(point);
}
return points;
}
通过这种方式,您实际上是在使用 Datapoint 实例,因此类型断言现在可以按预期工作。