Reputation: 1967
I trying to create a new date object for an ngx-chart following this example, specifically this code:
constructor() {
this.data = this.multi.map(group => {
group.series = group.series.map(dataItem => {
dataItem.name = new Date(dataItem.name);
return dataItem;
});
return group;
});
console.log(this.data);
}
I understand using new Date()as seen here but I keep getting this error: "Type 'Date' is not assignable to type 'string'." Which I also understand (because this is typescript), I just don't get how I am supposed to handle these two together. In the other examples I've seen this doesn't seem to be an issue.
Upvotes: 2
Views: 2473
Reputation: 9753
This is a case of type inference. you don't tell TS what type 'name' is. it sees the double quotes and infers a string. You have to tell TS that this is an any
.
You'll have to create an interface like this:
interface Multi{
name:String
series: Array<{value: number, name: any}> // <-- note here it's explicitly any
}
then you use it:
export var multi: Multi[] = [
{
"name": "Tunisia",
"series": [
{
"value": 3309,
"name": "2016-09-19T10:24:08.741Z"
}
...
]
},
{
"name": "El Salvador",
"series": [
{
"value": 5714,
"name": "2016-09-19T10:24:08.741Z"
},
....
]
}
]
Alternatively, instead of that long syntax in plunker, you can do this differently where TS would not mind like so:
this.data = multi.map(group =>
<any>{ // <-- tells TS this is explicitly any
"name": group.name,
"series": group.series.map(s => <any>{"value":s.value, "name":new Date(s.name)})
});
Upvotes: 2