Skip to content

Commit

Permalink
🥃 Infer return type of watch method when possible (react-hook-form#590)
Browse files Browse the repository at this point in the history
  • Loading branch information
axelboc authored and bluebill1049 committed Nov 28, 2019
1 parent 3fe45d1 commit 5614b44
Show file tree
Hide file tree
Showing 4 changed files with 12 additions and 10 deletions.
8 changes: 5 additions & 3 deletions app/src/conditionalField.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ let renderCounter = 0;

const ConditionalField: React.FC = () => {
const { register, handleSubmit, watch, formState } = useForm<{
selectNumber: string;
firstName: string;
lastName: string;
min: string;
Expand All @@ -27,9 +28,9 @@ const ConditionalField: React.FC = () => {
>
<select name="selectNumber" ref={register({ required: true })}>
<option value="">Select</option>
<option value={1}>1</option>
<option value={2}>2</option>
<option value={3}>3</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>

{selectNumber === '1' && (
Expand Down Expand Up @@ -73,6 +74,7 @@ const ConditionalField: React.FC = () => {
<button id="submit">Submit</button>
<div id="state">{JSON.stringify(formState)}</div>
<div id="result">{JSON.stringify(result)}</div>
<div id="result">{typeof selectNumber}</div>
<div id="renderCount">{renderCounter}</div>
</form>
);
Expand Down
2 changes: 1 addition & 1 deletion app/src/watch.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ const Watch: React.FC = () => {
firstName: string;
lastName: string;
};
toggle: string;
toggle: boolean;
}>();
const onSubmit = () => {};
const test = watch('test');
Expand Down
6 changes: 3 additions & 3 deletions src/contextTypes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,10 +38,10 @@ export interface FormContextValues<
unregister(names: FieldName<FormValues>[]): void;
unregister(names: FieldName<FormValues> | FieldName<FormValues>[]): void;
watch(): FormValues;
watch(
field: FieldName<FormValues>,
watch<T extends FieldName<FormValues>>(
field: T,
defaultValue?: string,
): FieldValue<FormValues>;
): FormValues[T];
watch(
fields: FieldName<FormValues>[],
defaultValues?: Partial<FormValues>,
Expand Down
6 changes: 3 additions & 3 deletions src/useForm.ts
Original file line number Diff line number Diff line change
Expand Up @@ -575,10 +575,10 @@ export default function useForm<FormValues extends FieldValues = FieldValues>({
}

function watch(): FormValues;
function watch(
field: FieldName<FormValues>,
function watch<T extends FieldName<FormValues>>(
field: T,
defaultValue?: string,
): FieldValue<FormValues>;
): FormValues[T];
function watch(
fields: FieldName<FormValues>[],
defaultValues?: Partial<FormValues>,
Expand Down

0 comments on commit 5614b44

Please sign in to comment.