diff --git a/src/random/draw.ts b/src/random/draw.ts index 6f2bfa11..ddef019b 100644 --- a/src/random/draw.ts +++ b/src/random/draw.ts @@ -16,10 +16,12 @@ import { random } from 'radashi' * ``` * @version 12.1.0 */ -export function draw(array: readonly T[]): T | null { +export function draw( + 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] diff --git a/tests/random/draw.test-d.ts b/tests/random/draw.test-d.ts new file mode 100644 index 00000000..af3b4f94 --- /dev/null +++ b/tests/random/draw.test-d.ts @@ -0,0 +1,28 @@ +import * as _ from 'radashi' + +describe('draw', () => { + test('variable with mutable array', () => { + const array = [1, 2, 3] + + expectTypeOf(_.draw(array)).toEqualTypeOf() + }) + + test('variable with empty array', () => { + const emptyArray = [] as never[] + const emptyTuple = [] as const + + expectTypeOf(_.draw(emptyArray)).toEqualTypeOf() + expectTypeOf(_.draw(emptyTuple)).toEqualTypeOf() + }) + + test('variable with tuple', () => { + const tuple = [1, 2, 3] as const + + expectTypeOf(_.draw(tuple)).toEqualTypeOf<1 | 2 | 3>() + }) + + test('inlined array', () => { + expectTypeOf(_.draw([])).toEqualTypeOf() + expectTypeOf(_.draw([1, 2, 3])).toEqualTypeOf<1 | 2 | 3>() + }) +})