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): improve draw signature for non-empty arrays #153

Merged
merged 11 commits into from
Nov 10, 2024
6 changes: 4 additions & 2 deletions src/random/draw.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,12 @@ import { random } from 'radashi'
* ```
* @version 12.1.0
*/
export function draw<T>(array: readonly T[]): T | null {
export function draw<const T extends readonly any[]>(
array: T,
): T extends readonly [any, ...any[]] ? T[number] : T[number] | null {
const max = array.length
if (max === 0) {
return null
return null as any
}
const index = random(0, max - 1)
return array[index]
Expand Down
28 changes: 28 additions & 0 deletions tests/random/draw.test-d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import * as _ from 'radashi'

describe('draw', () => {
test('variable with mutable array', () => {
const array = [1, 2, 3]

expectTypeOf(_.draw(array)).toEqualTypeOf<number | null>()
})

test('variable with empty array', () => {
const emptyArray = [] as never[]
const emptyTuple = [] as const

expectTypeOf(_.draw(emptyArray)).toEqualTypeOf<null>()
expectTypeOf(_.draw(emptyTuple)).toEqualTypeOf<null>()
})

test('variable with tuple', () => {
const tuple = [1, 2, 3] as const

expectTypeOf(_.draw(tuple)).toEqualTypeOf<1 | 2 | 3>()
})

test('inlined array', () => {
expectTypeOf(_.draw([])).toEqualTypeOf<null>()
expectTypeOf(_.draw([1, 2, 3])).toEqualTypeOf<1 | 2 | 3>()
})
})
Loading