'Cannot infer an array type with TypeScript
This is my code:
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'd like T to be ItemA when key is 'a' and ItemB when it's 'b'. In this way, values could be of type ItemA[] or ItemB[]. How could I achieve this?
I'm getting this 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'.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
