问题是你的函数对
MyGenericType
. 要让它知道此类型始终具有某些属性,需要添加约束。在这种情况下,看起来需要泛型类型是两个特定类型之一,因此可以告诉泛型函数:
MyGenericType
type PotentialType1 = {
id: string
name: string
someProperty: string
}
type PotentialType2 = {
id: string
name: string
someOtherProperty: string
}
const myFunction = <MyGenericType extends PotentialType1 | PotentialType2>(arrayOfObjects: MyGenericType[]) => {
return arrayOfObjects.map((obj: MyGenericType) => ({
id: obj.id,
name: obj.name,
someProperty: 'someProperty' in obj ? obj.someProperty : obj.someOtherProperty,
}))
}
TypeScript Playground
someProperty
obj
而不是抱怨这些属性在类型为的对象上不存在
PotentialType1 | PotentialType2