Typescript泛型选择器函数参数类型

huangapple go评论64阅读模式
英文:

Typescript Generic selector function argument type

问题

我正在尝试为我可重复使用的组件之一设置一个通用选择器函数。该函数的目标是从作为参数传递的对象中返回一个字符串或数字值。

函数签名定义如下:

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

在组件内部使用:

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 } />

我得到的错误如下:
Type '(row: Person) => string' is not assignable to type '<T>(row: T) => string | number'.
我还尝试在组件内修改我的参数类型为:
(row: object) => row.name,但然后我会收到一个错误,指出对象上未定义name属性。

我应该如何修改我的函数签名,以便它可以接受任何对象作为参数,只要函数返回字符串或数字

这似乎是一个非常标准的事情,但我无法理解。

英文:

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: &lt;T&gt;(row: T) =&gt; string | number
  // ...
}

Used inside of the component:

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

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

export type Gender = &quot;male&quot; | &quot;female&quot; | &quot;undisclosed&quot;

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

// ...

&lt;MyComponentName someProps={/* ... */} selector={ (row: Person) =&gt; row.name } /&gt;

The error I get is as follow:
Type &#39;(row: Person) =&gt; string&#39; is not assignable to type &#39;&lt;T&gt;(row: T) =&gt; string | number&#39;.
I also tried to modify my argument type inside of my component to :
(row: object) =&gt; 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.

答案1

得分: 1

尝试这个:

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

在另一篇帖子中解决

英文:

Try this:

type ComponentProps{
  selector: &lt;T extends unknown&gt;(row: T) =&gt; string | number
  // ...
}

Solved in another post

huangapple
  • 本文由 发表于 2023年2月16日 18:40:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/75471076.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定