Skip to content

Commit 8fec4e4

Browse files
committed
refactor(values-of): more consistent type inference
1 parent c9efa91 commit 8fec4e4

File tree

2 files changed

+11
-9
lines changed

2 files changed

+11
-9
lines changed

src/object/values-of/values-of.spec.ts

+9-5
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ import { valuesOf } from './index.js'
22

33
import { forAll, record, unknown, string, array, oneOf, integer } from '../../random/index.js'
44

5-
import { expect, it } from 'vitest'
5+
import { expect, it, expectTypeOf } from 'vitest'
66

77
it('valuesOf === Object.values', () => {
88
forAll(record(unknown()), (o) => {
@@ -30,8 +30,12 @@ it('valuesOf union object and array', () => {
3030
forAll(oneOf(array(string()), record([integer(), integer()])), (o) => {
3131
expect(valuesOf(o)).toStrictEqual(Object.values(o))
3232
})
33-
const _foo: number[] = valuesOf([1, 2, 3])
34-
const _foo2: (number | string)[] = valuesOf([1, '2', 3])
35-
const _foo3: 'bar'[] = valuesOf({ foo: 'bar' } as const)
36-
const _foo4: number[] | string[] = valuesOf<number[] | { foo: string }>({ foo: 'bar' })
33+
})
34+
35+
it('types', () => {
36+
expectTypeOf(valuesOf({ foo: 'bar' })).toEqualTypeOf<'bar'[]>()
37+
expectTypeOf(valuesOf<number[] | { foo: string }>({ foo: 'bar' })).toEqualTypeOf<number[] | string[]>()
38+
39+
expectTypeOf(valuesOf([1, 2, 3])).toEqualTypeOf<(1 | 2 | 3)[]>()
40+
expectTypeOf(valuesOf([1, '2', 3])).toEqualTypeOf<(1 | '2' | 3)[]>()
3741
})

src/object/values-of/values-of.ts

+2-4
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,4 @@
1-
import type { KeyOf } from '../../type/index.js'
2-
3-
export type ValuesOf<T> = T extends (infer I)[] ? I[] : T[KeyOf<T>][]
1+
export type ValuesOf<T extends ArrayLike<unknown> | {}> = T extends readonly (infer I)[] ? I[] : T[keyof T][]
42

53
/**
64
* Returns an array of values of the enumerable properties of an object.
@@ -23,6 +21,6 @@ export type ValuesOf<T> = T extends (infer I)[] ? I[] : T[KeyOf<T>][]
2321
*
2422
* @group Object
2523
*/
26-
export function valuesOf<T extends ArrayLike<unknown> | {}>(obj: T): ValuesOf<T> {
24+
export function valuesOf<const T extends ArrayLike<unknown> | {}>(obj: T): ValuesOf<T> {
2725
return Object.values(obj) as ValuesOf<T>
2826
}

0 commit comments

Comments
 (0)