有没有一种方法可以接受具有任意数量字段和任何类型但一个必填字段的对象数组,而不使用 "any" 类型?

Is there a way to accept array of objects with any number of fields and any type but one required field, not using the "any" type?

函数 printNames 必须接受对象数组,这些对象具有必填字段 name 和任何其他字段。

我不会用any

我无法改变IName

interface IName {
    name: string
}

const printNames = (items: Array<Combine<IName, { [key: string]: any }>>) => {
    items.forEach(item => console.log(item.name));
}

printNames([{ name: 'ook' }]);
printNames([{ age: 2, name: 'ook' }]);
printNames([{ lastName: 'test', name: 'ook' }]);

我想我应该以某种方式使用泛型,但不知道如何使用。

使用泛型并指明泛型类型应实现IName.

const printNames = <T extends IName>(items: Array<T>) => {
    items.forEach(item => console.log(item.name));
}