I am working with a third-party function, with a generic of type any
. That function returns an object of the type passed to it, and my own code works against that returned thing.
I'm trying to write my own generic function, which takes in a generic of type HasID
, and then passes that to the third-party function. However, when I attempt to access the ID
field of the return value from the third-party function, I get an error.
What do I need to do in order to type this properly?
type HasID struct {
ID string `json:"id"`
}
func ThirdPartyFunc[T any]() T {
// do some stuff
return someThing // of type T
}
func MyFunc[U HasID]() {
thingWithID := ThirdPartyFunc[U]()
fmt.Println(thingWithID.ID) // undefined (type U has no field or method ID)
}