Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(types): avoid inferring memo return type from key option #231

Merged
merged 1 commit into from
Aug 30, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion src/curry/memo.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import type { NoInfer } from 'radashi'

type Cache<T> = Record<string, { exp: number | null; value: T }>

function memoize<TArgs extends any[], TResult>(
Expand Down Expand Up @@ -56,7 +58,7 @@ export interface MemoOptions<TArgs extends any[]> {
*/
export function memo<TArgs extends any[], TResult>(
func: (...args: TArgs) => TResult,
options: MemoOptions<TArgs> = {},
options: MemoOptions<NoInfer<TArgs>> = {},
): (...args: TArgs) => TResult {
return memoize({}, func, options.key ?? null, options.ttl ?? null)
}
7 changes: 7 additions & 0 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,13 @@ export type ExtractNotAny<T, U> = Extract<[T] extends [Any] ? never : T, U>
export type SwitchAny<T, U> = [T] extends [Any] ? U : T
export type SwitchNever<T, U> = [T] extends [never] ? U : T

/**
* Prevent type inference on type `T`.
*
* @see https://github.com/microsoft/TypeScript/issues/14829#issuecomment-504042546
*/
export type NoInfer<T> = [T][T extends any ? 0 : never]

/**
* Extract types in `T` that are assignable to `U`. Coerce `any` and
* `never` types to unknown.
Expand Down
18 changes: 18 additions & 0 deletions tests/curry/memo.test-d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import * as _ from 'radashi'

describe('memo return type', () => {
test('memo with single argument key function', () => {
const foo = _.memo((a: string, b?: string) => {}, { key: a => a })
expectTypeOf(foo).toEqualTypeOf<
(a: string, b?: string | undefined) => void
>()
})

test('memo with two argument key function', () => {
const foo = _.memo((a: string, b?: string) => {}, { key: (a, b) => a })
expectTypeOf(foo).toEqualTypeOf<
(a: string, b?: string | undefined) => void
>()
foo('a')
})
})
Loading