Skip to content

Commit

Permalink
fix:fix conditional Typing in useSWRMutation to Allow Optional ExtraA…
Browse files Browse the repository at this point in the history
…rg Without Explicitly Passing Undefined (#2666)

* fix: add optional type

* fix: delete unused test

* fix: revert changes

* type: add case with optional ExtraArgs

* refactor: TriggerWithOptionalArgs -> TriggerWithOptionsArgs
  • Loading branch information
saengmotmi committed Jun 18, 2023
1 parent 55bfc88 commit 31832dc
Show file tree
Hide file tree
Showing 2 changed files with 57 additions and 0 deletions.
41 changes: 41 additions & 0 deletions mutation/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ export type SWRMutationConfiguration<
}

type RemoveUndefined<T> = T extends undefined ? never : T
type IsUndefinedIncluded<T> = undefined extends T ? true : false
export interface TriggerWithArgs<
Data = any,
Error = any,
Expand Down Expand Up @@ -87,6 +88,44 @@ export interface TriggerWithArgs<
): Promise<Data | undefined>
}

interface TriggerWithOptionsArgs<
Data = any,
Error = any,
SWRMutationKey extends Key = Key,
ExtraArg = never
> {
<SWRData = Data>(
extraArgument?: ExtraArg,
options?: SWRMutationConfiguration<
Data,
Error,
SWRMutationKey,
ExtraArg,
SWRData
>
): Promise<Data>
<SWRData = Data>(
extraArgument?: ExtraArg,
options?: SWRMutationConfiguration<
Data,
Error,
SWRMutationKey,
ExtraArg,
SWRData
> & { throwOnError: true }
): Promise<RemoveUndefined<Data>>
<SWRData = Data>(
extraArgument?: ExtraArg,
options?: SWRMutationConfiguration<
Data,
Error,
SWRMutationKey,
ExtraArg,
SWRData
> & { throwOnError: false }
): Promise<Data | undefined>
}

export interface TriggerWithoutArgs<
Data = any,
Error = any,
Expand Down Expand Up @@ -141,6 +180,8 @@ export interface SWRMutationResponse<
*/
trigger: [ExtraArg] extends [never]
? TriggerWithoutArgs<Data, Error, SWRMutationKey, ExtraArg>
: IsUndefinedIncluded<ExtraArg> extends true
? TriggerWithOptionsArgs<Data, Error, SWRMutationKey, ExtraArg>
: TriggerWithArgs<Data, Error, SWRMutationKey, ExtraArg>
/**
* Function to reset the mutation state (`data`, `error`, and `isMutating`).
Expand Down
16 changes: 16 additions & 0 deletions test/type/trigger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,22 @@ export function useTestSWRMutation() {
test()
}

export function useTestSWRMutationWithOptionalArgs() {
const { trigger } = useSWRMutation(
'key',
async (_, { arg }: { arg?: 'foo' }) => {
return arg?.toUpperCase()
}
)

const test = () => {
expectType<Promise<string | undefined>>(trigger('foo'))
expectType<Promise<string | undefined>>(trigger(undefined))
expectType<Promise<string | undefined>>(trigger())
}
test()
}

export function useTestSWRMutationWithSWRMutate() {
const { mutate } = useSWR('/some/key', () => {
return {
Expand Down

0 comments on commit 31832dc

Please sign in to comment.