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

refactor(shared): value utility #148

Merged
merged 1 commit into from
Feb 16, 2025
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
11 changes: 11 additions & 0 deletions packages/shared/src/value.test-d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,4 +19,15 @@ describe('value', () => {
expectTypeOf(value(() => Number(42))).toEqualTypeOf<Promise<number>>()
expectTypeOf(value(async () => Number(42))).toEqualTypeOf<Promise<number>>()
})

it('args', () => {
const v = {} as Value<string, [string, number]>
// @ts-expect-error missing args
value(v)
// @ts-expect-error missing args
value(v, 'hello')
value(v, 'hello', 123)
// @ts-expect-error wrong args
value(v, 'hello', '456')
})
})
4 changes: 0 additions & 4 deletions packages/shared/src/value.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,6 @@ it('value', async () => {
expect(await value(() => 42)).toBe(42)
expect(await value(async () => 42)).toBe(42)

expect(await value(() => ({
then: (resolve: (value: number) => void) => resolve(42),
}))).toBe(42)

expect(await value(async () => ({
then: (resolve: (value: number) => void) => resolve(42),
}))).toBe(42)
Expand Down
5 changes: 4 additions & 1 deletion packages/shared/src/value.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,10 @@ import type { Promisable } from 'type-fest'

export type Value<T, TArgs extends any[] = []> = T | ((...args: TArgs) => Promisable<T>)

export function value<T extends Value<any, TArgs>, TArgs extends any[] = []>(value: T, ...args: TArgs): Promise<T extends Value<infer U, any> ? U : never> {
export function value<T, TArgs extends any[]>(
value: Value<T, TArgs>,
...args: NoInfer<TArgs>
): Promise<T extends Value<infer U, any> ? U : never> {
if (typeof value === 'function') {
return (value as any)(...args)
}
Expand Down