Here is the code snippet I'm working with:
interface ItemA{
x:number
y:string
}
interface ItemB{
z:boolean
}
interface Data{
a:ItemA[]
b:ItemB[]
bool:boolean
}
type ItemType=keyof Data&('a'|'b')
function f<K extends ItemType>(data:Data,key:K):void{
type T=Data[K] extends (infer TT)[]?TT:never
const values:T[]=data[key]
values.forEach(
(t:T):void=>{
console.log(t)
}
)
}
I want to assign T
variable to be of type ItemA
when the key
parameter is equal to 'a'
, and of type ItemB
when it's 'b'
. This way, the values
array could either be of type ItemA[]
or ItemB[]
. How can I make this work?
When trying to implement this functionality, I encountered the following TypeScript error:
20:9 Type 'ItemA[] | ItemB[]' is not assignable to type 'T[]'.
Type 'ItemA[]' is not assignable to type 'T[]'.
Type 'ItemA' is not assignable to type 'T'.