[v2] Support type narrowing for union form types

オープン
#2,297 コメント 0 件 リアクション 0 件 担当者 0 名 GitHub で見る

メンテナーはふだん 1 日以内に返信

まだ誰も着手していません。

評価

難易度
5/5
見積もり時間
1週間以上
初心者へのやさしさ
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時間
マージ済み PR(30日)
14

環境構築

はじめの一歩

  1. issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
  2. 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
  3. リポジトリをフォークし、ブランチを切って変更します。
  4. issue 番号を参照したプルリクエストを送ります。

TanStack/form のほかの issue

TanStack/form の issue をすべて見る

似ている issue

TypeScript の issue をもっと見る

新しい issue をメールで受け取る

初心者向けの GitHub issue を短くまとめたダイジェスト。