0

I'm trying to set a generic selector function for one of my reusable component. The goal of this function is to return a string or number value from an object that is passed as an argument.

The function signature is defined as follows:

type ComponentProps{
  selector: <T>(row: T) => string | number
  // ...
}

Used inside of the component:

export const data = [
  {
    name: "John Doe",
    age: 30,
    job: "Software Engineer",
    pets: {
      dogs: 1,
      cats: 2,
      turtles: 0,
    }
  }
  // ...
]

export type Pets = { dogs: number; cats: number; turtles: number }

export type Gender = "male" | "female" | "undisclosed"

export type Person = {
  name: string
  age: number
  job: string
  pets: Pets
  gender: Gender
}

// ...

<MyComponentName someProps={/* ... */} selector={ (row: Person) => row.name } />

The error I get is as follow: Type '(row: Person) => string' is not assignable to type '<T>(row: T) => string | number'. I also tried to modify my argument type inside of my component to : (row: object) => row.name but then i get an error stating that the name property is not defined on the object.

How could I modify my function signature so it can receive any object as an argument as long as the function returns a string or a number?

This seems like a pretty standard thing to do but I cannot wrap my head around it.

BJRINT
  • 639
  • 3
  • 8
  • 1
    Sounds like what you need is `selector:(row: any) => string | number` [playground](https://www.typescriptlang.org/play?#code/C4TwDgpgBAwg9gWzHAdhFwAKAnOYDOUAvFAN4BQUU+EANhAMbBzYBcUAFLgO7sCGKEAEpiAPigoArggBGEbFAA+1YNgCWKAObkAvuXINU+YFEjZ8qdvCSp0WXAWJlKVanUbM2nHuymz5IkTiPFAA1FAAjLpAA) – JuliusAlphonso Feb 16 '23 at 11:37

1 Answers1

1

Try this:

type ComponentProps{
  selector: <T extends unknown>(row: T) => string | number
  // ...
}

Solved in another post

AlvaroPR
  • 72
  • 6