Skip to content

Commit bcdc9a1

Browse files
committed
types: add U of field<T, U>() to pass the preferred type as the result of toObject()
1 parent e587c4e commit bcdc9a1

File tree

2 files changed

+17
-7
lines changed

2 files changed

+17
-7
lines changed

docs/api/field.md

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,14 @@ This function takes an initial value and a yup schema.
33
This function returns `Field` object.
44

55
## Parameters
6-
The `field()` takes 3 parameters:
6+
The `field()` takes 3 parameters and 2 generic type parameters:
77

88
```typescript
9-
function field<T>(value: T | Ref<T>, schema?: FieldSchema, validateOptions?: ValidateOptions): Field<T>
9+
function field<T, U extends T = T>(
10+
value: T | Ref<T>,
11+
schema?: FieldSchema,
12+
validateOptions?: ValidateOptions
13+
): Field<T, T extends U ? T : U>;
1014
```
1115

1216
### 1. `value` <Badge type="danger" text="Required" />
@@ -67,6 +71,12 @@ Since `validateSync()` is used internally, Async tests are not available.
6771
### 3. `validateOptions` <Badge type="info" text="Optional" />
6872
- Pass `{ abortEarly: false }` if all validation errors by the yup schema are required.
6973

74+
### `T` <Badge type="info" text="Optional" />
75+
- Pass the type of `$value` explicitly like `ref<T>()`.
76+
77+
### `U` <Badge type="info" text="Optional / Default: T" />
78+
- Pass the preferred type as the result of [`toObject()`](/api/toObject).
79+
7080
## Details of `Field` object
7181
### `$value` property
7282
- The field value that can be set to `v-model`.

src/index.ts

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@ export type FormPropType<T extends () => Form> = PropType<
3232
ReturnType<T> & { $key?: number }
3333
>;
3434

35-
class Field<T> {
35+
class Field<T, U extends T = T> {
3636
private readonly $_valueRef: Ref<T>;
3737
private readonly $_errorRef: ComputedRef<yup.ValidationError | undefined>;
3838
public readonly $label: string;
@@ -210,11 +210,11 @@ export function defineForm<T extends Form>(form: T): T {
210210
return form;
211211
}
212212

213-
export function field<T>(
213+
export function field<T, U extends T = T>(
214214
value: T | Ref<T>,
215215
schema?: FieldSchema,
216216
validateOptions?: ValidateOptions
217-
): Field<T> {
217+
): Field<T, T extends U ? T : U> {
218218
return new Field(value, schema, validateOptions);
219219
}
220220

@@ -268,8 +268,8 @@ type ToObjectOutput<T extends Form> = {
268268
? never
269269
: Exclude<K, "$key">]: T[K] extends Form
270270
? ToObjectOutput<T[K]>
271-
: T[K] extends Field<any>
272-
? T[K]["$value"]
271+
: T[K] extends Field<any, infer U>
272+
? U
273273
: T[K] extends FormsField<(arg: any) => Form>
274274
? ToObjectOutput<T[K]["$forms"][number]>[]
275275
: never;

0 commit comments

Comments
 (0)