[英]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'
.我希望T
在key
为'a'
时为ItemA
,在键为'b'
时为ItemB
。 In this way, values
could be of type ItemA[]
or ItemB[]
.这样, values
可以是ItemA[]
或ItemB[]
类型。 How could I achieve this?我怎么能做到这一点?
I'm getting this TypeScript error:我收到此 TypeScript 错误:
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'.
Like this?像这样?
interface ItemA{
x:number
y:string
}
interface ItemB{
z:boolean
}
interface Data{
a: ItemA[]
b: ItemB[]
bool: boolean
}
type ItemType = 'a' | 'b';
function f(data: Data, key: ItemType): void
{
type T = Data[typeof key]
const values: T = data[key]
values.forEach(
(t: ItemA | ItemB) => {
console.log(t)
}
)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.