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

Array#isArray is too eager to infer unknown #4200

Closed
danielnixon opened this issue Dec 29, 2024 · 1 comment
Closed

Array#isArray is too eager to infer unknown #4200

danielnixon opened this issue Dec 29, 2024 · 1 comment
Labels
enhancement New feature or request

Comments

@danielnixon
Copy link

danielnixon commented Dec 29, 2024

What is the problem this feature would solve?

// Given something like this:
declare const maybeArray: number | readonly number[];

// Array.isArray is more difficult to use than it could be because it
// is too eager to infer its argument (and therefore return) type to unknown[]
// Type 'unknown' is not assignable to type 'number'.
// @ts-expect-error
export const definitelyArray: readonly number[] = Array.isArray(maybeArray) ? maybeArray : [maybeArray];

// Help inference with an explicit type param
export const definitelyArray2: readonly number[] = Array.isArray<typeof maybeArray>(maybeArray) ? maybeArray : [maybeArray];

What is the feature you are proposing to solve the problem?

Redefine isArray more like this:

declare const maybeArray: number | readonly number[];
declare const maybeArray2: unknown;

// If isArray was instead defined simply like this:
export const isArray = <T>(self: T): self is Extract<T, ReadonlyArray<unknown>> => Array.isArray(self)

// Then type inference would work without an explicit type argument
// const definitelyArray: readonly number[]
export const definitelyArray = isArray(maybeArray) ? maybeArray : [maybeArray];

// And the unknown case would still work as expected
// const definitelyArray2: unknown[]
export const definitelyArray2 = isArray(maybeArray2) ? maybeArray2 : [maybeArray2];

What alternatives have you considered?

No response

@danielnixon danielnixon added the enhancement New feature or request label Dec 29, 2024
@danielnixon
Copy link
Author

Oh, this is probably a dupe of #4051

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

1 participant