[v2] Support type narrowing for union form types

未關閉
#2,297 0 則留言 0 個 reaction 已指派 0 人 在 GitHub 檢視

維護者通常 1 天內回覆

還沒有人認領這個 Issue。

評估

難度
5/5
預估耗時
一週以上
新手友好度
35/100
Issue 類型
功能
描述清晰度
需要釐清
活躍度
冷清
技術堆疊
react, typescript
領域
frontend

研究方向

先檢視 formOptions 和 ReactFormType 的 TypeScript 定義,重點關注聯合表單型別和聯合值的表示方式。將所需的型別謂詞行為與現有的表單 API 進行比較。當述詞能將表單縮小為對應的聯合成員,且縮小後仍可使用 form.Field 等成員時,即表示完成。

由索引模型根據 Issue 內容生成。

描述

area: types scope: core type: enhancement

In v2, a component may need to accept a form created from one of several sets of form options:

const formVariant1 = formOptions(/* ... */)
const formVariant2 = formOptions(/* ... */)

type Form1 = ReactFormType<typeof formVariant1>
type Form2 = ReactFormType<typeof formVariant2>


interface MyComponentProps {
  form: Form1 | Form2
}

TypeScript cannot resolve the resulting union of form types correctly. Once form is typed as Form1 | Form2, members such as form.Field are no longer available.

A related problem occurs when a form's values are represented by a union. Even after checking a discriminant, such as form.state.values.type === 'A', TypeScript does not narrow the type of the form itself. APIs that are only valid for type A therefore remain unavailable even though the value has already been narrowed.

It would be useful to have an API that narrows the form alongside its values. A user could provide a type predicate for one member of the union and, when that predicate succeeds, work with a form typed specifically for that member.

Some thoughts

The exact API is open for discussion, but a possible design would:

  • accept formOptions whose data type is a union;
  • accept a callback that acts as a type predicate, narrowing TData to one of its members (TGuard);
  • expose a form type narrowed to TGuard; and
  • provide a function, essentially a wrapper around the original predicate, that can accept the TData form and narrow it to the corresponding TGuard form.
主要語言
TypeScript
星號
6.8k
分支
717
平均合併
5 天 22 小時
30 天內合併 PR
14

環境準備

從這裡開始

  1. 先讀完整個 Issue,再讀專案的貢獻指南。
  2. 在 Issue 下留言說明你要接手 —— 這能避免兩個人做同樣的事。
  3. Fork 儲存庫,在一個分支上完成修改。
  4. 送出 Pull Request,並在描述裡引用這個 Issue 編號。

TanStack/form 的其他 Issue

查看 TanStack/form 的全部 Issue

相似的 Issue

更多 TypeScript Issue

把新 issue 寄到你的電子郵件信箱

精選適合新手參與的 GitHub issue 摘要。