簡體   English   中英

如何使用 React JSX 在 Typescript 中實現通用箭頭 function 作為接口屬性

[英]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;
}

我希望valuenewValue的類型相同,但它們可以是任何東西。

我有一個組件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)} /> },
  ]}
/>

錯誤在於我傳遞給onChangeselectedRole值,並說

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 的值? 如何強制valuenewValue為同一類型,但仍為任何類型?

好的,我似乎找到了解決方法:

通過創建一個

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM