[英]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.