![](/img/trans.png)
[英]How to create a generic arrow function with react and typescript
[英]How to implement a generic arrow function as interface property in Typescript with React JSX
我正在尝试创建一个
interface PromptInput {
key: string,
title: string,
customInput?: <T>(value: T, onChange: (newValue: T) => void) => React.ReactNode;
}
我希望value
和newValue
的类型相同,但它们可以是任何东西。
我有一个组件InputPromptDialog
它有一个道具inputs: PromptInput[]
但是当我尝试通过 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)} /> },
]}
/>
错误在于我传递给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)
为什么没有推断出 T 的值? 如何强制value
和newValue
为同一类型,但仍为任何类型?
好的,我似乎找到了解决方法:
通过创建一个
type PromptInputCustomInput<T> = (value: T, onChange: (newValue: T) => void) => React.ReactNode;
并将界面更改为:
interface PromptInput {
key: string,
title: string,
customInput?: PromptInputCustomInput<any>;
}
并将我通过 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> },
]}
/>
这会产生我正在寻找的预期结果。 但我仍然很想知道是否有一种方法可以做到这一点,而不必总是将我传递的值as PromptInputCustomInput<DESIRED_TYPE>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.