Below is the JSON data:
let JSON_RESPONSE = `{"birthDates": ["2017-01-02","2016-07-15"]}`
There is a TypeScript
object called Children
with an array of Date
objects and an ES6
constructor:
class Children {
birthDates: Date[] = []
constructor(values: Object = {}) {
Object.assign(this, values)
}
}
The goal is to initialize this object using the JSON data to convert the dates:
const children = new Children(JSON.parse(this.JSON_RESPONSE))
children.birthDates.forEach(it => {
console.log(it.getDate())
})
However, since Children#birthDates
are stored as Object
types instead of Date
, explicit new Date()
initialization is needed:
children.birthDates.forEach(it => {
console.log(new Date(it).getDate())
})
The question remains on how to convert JSON data to valid Date
objects within the constructor without manual property mapping.
It seems that Object.assign
is not suitable for deep type inheritance as it only performs a shallow copy.