it might be a silly question but I am struggling a bit with the following interfaces. I have two objects:
interface Apple {
color: 'red' | 'green'
}
interface Orange {
variety: 'normal' | 'blood'
}
interface Banana {
plantain: boolean
}
interface A {
bananas: Banana[],
oranges: Orange[],
apples: Apple[],
lookAtBanana: (banana: Banana) => Banana,
}
interface B {
bananas: Banana[],
apples: Apple[]
}
const mergeObjectsOption1 = (state: A, response: B) => {
for (const key in response) {
state[key] = response[key] // Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'B'.
}
}
const mergeObjectsOption2 = (state: A, response: B) => {
for (const key in response) {
const typedKey = key as keyof typeof response
const value = response[typedKey];
state[typedKey] = value; // this is as close as I get to the desired output,but still doesn't work
}
}
}
So, what's the best way to do such simple operation while retaining typings throughout in Typescript? I guess am operator that extracts a single type from a union based on a variable would help, but can't find any :/
As an additional note type A is actually a this
context for a VueJS component.
Playground here: https://stackblitz.com/edit/typescript-3xbbzd?file=index.ts