[英]How to implement a generic arrow function as interface property in Typescript with React JSX
I am trying to create an我正在尝试创建一个
interface PromptInput {
key: string,
title: string,
customInput?: <T>(value: T, onChange: (newValue: T) => void) => React.ReactNode;
}
I want the types of value
and newValue
to be the same, but they can be anything.我希望
value
和newValue
的类型相同,但它们可以是任何东西。
I have a component InputPromptDialog
which has a prop inputs: PromptInput[]
我有一个组件
InputPromptDialog
它有一个道具inputs: PromptInput[]
But when I try to pass arguments I get an error:但是当我尝试通过 arguments 时出现错误:
<InputPromptDialog
inputs={[
{ key: 'fullName', title: 'Full Name' },
{ key: 'email', title: 'Email' },
{ key: 'role', title: 'Role', customInput: (value, onChange) => <RoleSelector onChange={(selectedRoleId: string) => onChange(selectedRoleId)} /> },
]}
/>
The error is with the selectedRole
value I am passing to onChange
, and says错误在于我传递给
onChange
的selectedRole
值,并说
Argument of type 'string' is not assignable to parameter of type 'T'.
'T' could be instantiated with an arbitrary type which could be unrelated to 'string'.ts(2345)
Why is the value of T not inferred?为什么没有推断出 T 的值? How can I enforce
value
and newValue
to be the same type, but still be any type?如何强制
value
和newValue
为同一类型,但仍为任何类型?
Ok, I seem to have figured out a fix:好的,我似乎找到了解决方法:
By creating a通过创建一个
type PromptInputCustomInput<T> = (value: T, onChange: (newValue: T) => void) => React.ReactNode;
and changing the interface to:并将界面更改为:
interface PromptInput {
key: string,
title: string,
customInput?: PromptInputCustomInput<any>;
}
and changing where I pass the arguments to:并将我通过 arguments 的位置更改为:
<InputPromptDialog
inputs={[
{ key: 'fullName', title: 'Full Name' },
{ key: 'email', title: 'Email' },
{ key: 'role', title: 'Role', customInput: ((value, onChange) => <RoleSelector onChange={(selectedRoleId: string) => onChange(selectedRoleId)} />) as PromptInputCustomInput<string> },
]}
/>
This creates the desired result I am looking for.这会产生我正在寻找的预期结果。 But I would still be interested to know if there is a way of doing this without having to always cast the values I am passing
as PromptInputCustomInput<DESIRED_TYPE>
但我仍然很想知道是否有一种方法可以做到这一点,而不必总是将我传递的值
as PromptInputCustomInput<DESIRED_TYPE>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.