I am relatively new to Typescript, so please bear with me as I navigate through this challenge.
In a specific use-case scenario I have created an array that can contain instances of both "Class One" and "Class Two". My goal is to iterate through this array using a forEach loop and perform actions when the property 'drawer' is present.
However, I encounter an issue in Typescript while trying to access 'drawer' within the forEach loop:
Property 'drawer' does not exist on type 'One | Two'.
Property 'drawer' does not exist on type 'Two'.
Even though 'drawer' is clearly present in 'One'.
If I set 'arrayWithBothOneAndTwo' to
let arrayWithBothOneAndTwo = [] as One[]
, it resolves the error, but I know this isn't the best solution since the array can also contain instances of 'Two', leading to possible errors.
If I modify the forEach loop like this:
arrayWithBothOneAndTwo.forEach((item: One) => {
console.log(item.drawer)
})
This results in another error:
Argument of type '(item: One) => void' is not assignable to parameter of type '(value: One | Two, index: number, array: (One | Two)[]) => void'.
Types of parameters 'item' and 'value' are incompatible.
Type 'One | Two' is not assignable to type 'One'.
Property 'drawer' is missing in type 'Two' but required in type 'One'.
To summarize:
I need a way to access 'item.drawer' within my forEach loop without causing any errors in my code. Any suggestions or solutions would be greatly appreciated!
class One {
drawer: string[] = []
constructor () {
this.drawer.push('A')
this.drawer.push('B')
this.drawer.push('C')
}
}
class Two {
notADrawer: string[] = []
constructor () {
this.notADrawer.push('D')
this.notADrawer.push('E')
this.notADrawer.push('F')
}
}
// Create arrays with instances of One and Two classes
const someOnes = [new One(), new One()]
const someTwos = [new Two(), new Two(), new Two(), new Two()]
// Initialize an array that can hold instances of One or Two
let arrayWithBothOneAndTwo: Array<One | Two> = []
// Populate the array with instances of One and Two classes
arrayWithBothOneAndTwo = [...someOnes, ...someTwos]
// Iterate through the array and display the 'drawer' array if present
arrayWithBothOneAndTwo.forEach((item) => {
console.log(item.drawer)
})