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

Better type signature for random's sample() #6159

Open
lionel-rowe opened this issue Oct 30, 2024 · 0 comments
Open

Better type signature for random's sample() #6159

lionel-rowe opened this issue Oct 30, 2024 · 0 comments

Comments

@lionel-rowe
Copy link
Contributor

lionel-rowe commented Oct 30, 2024

Is your feature request related to a problem? Please describe.

Currently, the type signature for sample() is correct, but often overly broad, as it always includes undefined:

// type is number | undefined, even though we know it can only be 1, 2, or 3 (never undefined)
sample([1, 2, 3])

Describe the solution you'd like

sample() to narrow the type to exclude undefined in cases where TS can determine it statically.

The current signature is roughly this:

declare function sample<T>(array: ArrayLike<T>): T | undefined

A signature something like the following would be an improvement:

declare function sampleNext<const T extends ArrayLike<unknown>>(array: T):
    T extends { 0: unknown }
        ? T[keyof T & number]
        : T[keyof T & number] | undefined

TS Playground

Describe alternatives you've considered

The only case I can think of where this would lead to runtime types diverging from TS types is where the argument is statically detected to be an array-like with a 0 property but also having a spoofed length of 0, e.g. { 0: 'xyz', length: 0 }.

If that can't be fixed through further refinements of the type signature, it could be solved either by:

  • Checking type of length is not 0 (but that still wouldn't detect where type is { 0: string, length: number } but length is 0 at runtime)
  • Throwing at runtime on such inputs
  • Simply assuming they won't occur in real-world scenarios (a reasonable assumption, and if they do occur it's likely to be due to a deeper underlying bug).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant