[v2] Support type narrowing for union form types

Đang mở
#2,297 0 bình luận 0 reaction 0 người được giao Xem trên GitHub

Maintainer thường phản hồi trong vòng 1 ngày

Chưa có ai nhận issue này.

Đánh giá

Độ khó
5/5
Thời gian dự kiến
Hơn một tuần
Mức phù hợp với người mới
35/100
Loại issue
Tính năng
Độ rõ ràng
Cần làm rõ
Mức độ hoạt động
Ít trao đổi
Công nghệ
react, typescript
Lĩnh vực
frontend

Hướng nghiên cứu

Bắt đầu bằng cách xem lại các định nghĩa TypeScript cho formOptions và ReactFormType, tập trung vào cách các kiểu form union và các giá trị union được biểu diễn. So sánh hành vi mong muốn của type predicate với form API hiện có. Hoàn thành khi một predicate có thể thu hẹp form thành union member tương ứng và các member như form.Field vẫn khả dụng sau khi thu hẹp.

Do mô hình lập chỉ mục viết ra từ nội dung của issue.

Mô tả

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.
Ngôn ngữ chính
TypeScript
Star
6.8k
Fork
717
Merge trung bình
5 ngày 22 giờ
Pull request đã merge (30 ngày)
14

Chuẩn bị môi trường

Bắt đầu từ đâu

  1. Đọc hết issue, rồi đọc hướng dẫn đóng góp của dự án.
  2. Bình luận trên issue rằng bạn sẽ nhận — tránh hai người làm cùng một việc.
  3. Fork repository và làm thay đổi trên một nhánh.
  4. Mở pull request có tham chiếu số hiệu của issue.

Issue khác của TanStack/form

Tất cả issue của TanStack/form

Issue tương tự

Thêm issue về TypeScript

Nhận issue mới trong hộp thư của bạn

Bản tóm tắt ngắn những issue GitHub phù hợp với người mới.