I want to elegantly copy a typescript struct interfaceName
(which satisfies a certain interface). This TypeScript contains a map attribute3
of Type Map<IKey, number>
, which perhaps has to be modified (depending on a condition): An additional key value pair has to be inserted.
IKey
, again, is an interface.
interface InterfaceName{
attribute1: string
attribute2: string
attribute3: Map<IKey, number>
}
interface IKey{
a1: number
a2: number
}
}
My attempt was the following: I just use the ...
syntax to copy all the members of interfaceName
and then try to assign attribute3
a modified copy.
But somehow this does not work: In the end the same Map object is passed out of the function, regardless of the boolean.
const createModifiedCopyIfWished = (interfaceName: InterfaceName, wished: Boolean) => wished ? {
...interfaceName,
attribute3: interfaceName.attribute3.set({a1:1,a2:2},5)
}
:
interfaceName
let a: InterfaceName = {
attribute1: "a",
attribute2: "b",
attribute3: new Map<IKey, number>()
}
let b = createModifiedCopyIfWished(a, true)
// {"attribute1":"a","attribute2":"b","attribute3":{}}
console.log(JSON.stringify(b))
What is the prober way to do this? Is it even possible within one statement?
Working example: LiveCode