按Typescript中子类型的键索引超类型

按Typescript中子类型的键索引超类型,typescript,typescript-generics,Typescript,Typescript Generics,我有以下代码: type Foo = { foo: string } type Bar = { bar: string } type FooAndBar = Foo & Bar function fn<T extends Foo | Bar>(list: Array<T>, key: keyof T, acc: FooAndBar) { for (const elem of list) { acc[key] = elem[key] //

我有以下代码:

type Foo = { foo: string }
type Bar = { bar: string }
type FooAndBar = Foo & Bar 

function fn<T extends Foo | Bar>(list: Array<T>, key: keyof T, acc: FooAndBar) {
    for (const elem of list) {
        acc[key] = elem[key] // ERROR: Type 'keyof T' cannot be used to index type 'FooAndBar'
    }
}


const foos:Foo[] = [{foo: "a"}, {foo: "b"}]
const bars:Bar[] = [{bar: "x"}, {bar: "y"}]

const acc: FooAndBar = { foo: "", bar: "" }
fn(foos, "foo", acc)
fn(bars, "bar", acc)
type Foo={Foo:string}
类型Bar={Bar:string}
输入FooAndBar=Foo&Bar
函数fn(列表:数组,键:keyof T,acc:FooAndBar){
for(列表常量){
acc[key]=elem[key]//错误:类型“keyof T”不能用于索引类型“FooAndBar”
}
}
常量foos:Foo[]=[{Foo:a},{Foo:b}]
常数条:条[]=[{Bar:x},{Bar:y}]
常量acc:FooAndBar={foo:,bar:}
fn(foos,“foo”,acc)
fn(钢筋,“钢筋”,acc)

我遇到一个编译错误,
Type'keyof T'不能用于在上面注释的行上索引Type'FooAndBar'
。我可以添加哪些类型约束来进行类型检查?

从您的示例中,我假设您希望将每个数组的最新元素累积到公共
acc
变量中

在这种情况下,您可以使
fn
更通用:

函数fn(列表:数组,键:keyof T,acc:T){
for(列表常量){
acc[键]=元素[键];
}
}
因此,您可以传递任何数组,acc的唯一要求是与项的类型相同

这是一份完整的

示例代码无法工作,因为您的
key
参数的类型为
keyof(Foo | Bar)
never
:即
Foo
Bar
没有共同的键