Reputation: 507
I have component that gets data from a class/model (projInfo), including a date object. I need to use the different parts of the date (day/month/year) formatted such that i need to break them up and put them in an array.
I can't seem to parse the Date object into a string[] type. Here's what I have:
public _startDate = this.projInfo.startdato; //.toString();
@Input()
set startDate(startDate: string) {
// remove commas then split into array
const d: string = this.startDateFormat.replace(',', '');
this._startDate = d.split(' ');
}
"this._startDate" on last line provides and error Type 'string[]' is not assignable to type 'string'
.
How do I solve this? It's hard to search for answers because I think the error is too broad.
Upvotes: 0
Views: 5104
Reputation: 469
When you initialize a class variable and assign it a value like
public _startDate = this.projInfo.startdato;
and this.projInfo.startdato has the type string, the typescript compiler will assume the type of _startDate to be a string as well. Since the split method of a string: String.prototype.split() will return an array the compiler complains.
You have to decide which type your _startDate variable should be. I don't know what this.projInfo.startdato is so i can not give you any solution for that.
Generally you could initialize your variable with a type like:
public _startDate: Array<string> = [this.projInfo.startdato];
And typecasting in typescript would work like
this._startDate = <string> d.split(' '); // I guess this still won't work in this case
Upvotes: 1