英文:
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: <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.
答案1
得分: 1
尝试这个:
type ComponentProps{
selector: <T extends unknown>(row: T) => string | number
// ...
}
英文:
Try this:
type ComponentProps{
selector: <T extends unknown>(row: T) => string | number
// ...
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论