Having the following json
[
{
"Value": "100000000",
"Duration": 1
},
{
"Value": "100000001",
"Duration": 2
},
{
"Value": "100000002",
"Duration": 3
},
{
"Value": "100000003",
"Duration": 5
},
{
"Value": "100000004",
"Duration": 0
},
{
"Value": "100000005",
"Duration": 8
},
{
"Value": "100000006",
"Duration": 10
}
]
and the following definition
interface Duration {
value: string
duration: number
}
I would like to have a method on Duration interface to be available in all objects
durationInSeconds():number {
return duration*1000
}
The usage scenario would be:
const all = previousJsonContent
const durations:Duration[] = parseAsObjects(all) // JSON.parse(all)
const firstInSeconds = durations[0].durationInSeconds()
Typescript approach
What is idiomatic to typescript? What is the least intrusive way? Should I use assign
, prototype
, mixins
? The problem is that deserialized json is just a data container while I want to treat it as full Objects with methods assigned according to the types and ideally also deep, at fields that also should have a type.
Scala approach
In scala I would create a value class wrapper around the data without performance penalty and use some implicit magic like in https://www.baeldung.com/scala/rich-wrappers