I am faced with a scenario where I have an object that can take on two different shapes:
{ageTop:42}
or
{locations: [{name:Myrtle Beach}]}
These objects are passed as parameters to a function, and I want to ensure that the function only receives the types it can work with. It could be one of these objects, both, or none.
To address this, I have devised a solution by defining interfaces and types as follows:
interface locationsType {
locations: Array<{name: string}>
}
interface ageTopType {
ageTop: number
}
type keyType = 'ageTop' | 'locations'
I aim to enforce the correct usage of interfaces based on the selected key value by using conventions in my code. However, I am concerned about potential errors that may arise if these conventions are not adhered to. How can I reinforce this through typing? Essentially, I want to implement a simple logic that looks like this:
interface traitType {
key: keyType
value: this.key === 'locations' ? locationsType : ageTopType;
}
class Developer {
locations: []
ageTop;
constructor(ageTop,locations) {
this.ageTop = ageTop
locations.forEach(_val => this.locations.push(_val))
}
loadTrait(trait:TraitType) {
if(trait.key === location) {
this.trait.value.forEach(_val => this.locations.push(_val)
return
}
this[trait.key] = trait.value;
}
}
I have attempted the above approach but encountered some issues. Any suggestions or insights?