Skip to content

Commit

Permalink
fix: better isArray return type
Browse files Browse the repository at this point in the history
  • Loading branch information
aleclarson committed Jul 3, 2024
1 parent cafc7fc commit 9a4a97d
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 2 deletions.
11 changes: 9 additions & 2 deletions src/typed/isArray.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,9 @@
export const isArray: (value: unknown) => value is readonly any[] =
Array.isArray
export const isArray = Array.isArray as <Input>(
value: Input,
) => value is readonly any[] extends Extract<Input, readonly any[]>
? Extract<Input, readonly any[]>
: any[] extends Extract<Input, any[]>
? Extract<Input, any[]>
: unknown[] extends Input
? unknown[]
: never
44 changes: 44 additions & 0 deletions tests/typed/isArray.test-d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import * as _ from 'radashi'

describe('isArray return type', () => {
test('value is unknown', () => {
const value = {} as unknown
if (_.isArray(value)) {
expectTypeOf(value).toEqualTypeOf<unknown[]>()
} else {
expectTypeOf(value).toEqualTypeOf<unknown>()
}
})
test('value is string', () => {
const value = {} as string
if (_.isArray(value)) {
expectTypeOf(value).toEqualTypeOf<never>()
} else {
expectTypeOf(value).toEqualTypeOf<string>()
}
})
test('value is string or ReadonlyMap', () => {
const value = {} as string | readonly string[]
if (_.isArray(value)) {
expectTypeOf(value).toEqualTypeOf<readonly string[]>()
} else {
expectTypeOf(value).toEqualTypeOf<string>()
}
})
test('value is string, ReadonlyMap, or Map', () => {
const value = {} as string | readonly string[] | string[]
if (_.isArray(value)) {
expectTypeOf(value).toEqualTypeOf<readonly string[] | string[]>()
} else {
expectTypeOf(value).toEqualTypeOf<string>()
}
})
test('value is string or Map', () => {
const value = {} as string | string[]
if (_.isArray(value)) {
expectTypeOf(value).toEqualTypeOf<string[]>()
} else {
expectTypeOf(value).toEqualTypeOf<string>()
}
})
})

0 comments on commit 9a4a97d

Please sign in to comment.