Here is the JSON data I have:
let JSON_RESPONSE = `{"birthDates": ["2017-01-02","2016-07-15"]}`
I have a TypeScript
object with an array of Date
objects and a constructor that uses ES6
features:
class Children {
birthDates: Date[] = []
constructor(values: Object = {}) {
Object.assign(this, values)
}
}
I am trying to initialize this object using the JSON data provided:
const children = new Children(JSON.parse(this.JSON_RESPONSE))
children.birthDates.forEach(date => {
console.log(date.getDate())
})
The issue arises because Children#birthDates
are assigned as type Object
instead of Date
. By explicitly converting them to Date
, it resolves the problem:
children.birthDates.forEach(date => {
console.log(new Date(date).getDate())
})
My question is how can I seamlessly convert JSON data into valid Date
objects during the object's initialization without manually mapping each property.
It seems like Object.assign
does not meet my requirements and only performs a shallow
copy rather than a deep
copy with type inheritance.