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

Would It Be Possible to Update the Typing of max([0, anyNumber]) Such That It Returns Number? #5783

Open
klondikemarlen opened this issue Nov 30, 2023 · 3 comments

Comments

@klondikemarlen
Copy link

Context

Would it be possible to update the typing of max([0, someNumberVariable]) such that it returns number?

Given this Typescript code

max([0, someNumberVariable])

I would expect the type to be a number.
Instead the type is number | undefined
So in practice, I need to write the function as

max([0, someNumberVariable]) as number

I've done weirder things with TypeScript in the past, so it seems likely that this would be possible, but I can't even find the definition of max in the Lodash repo, so I might not be correct.

@klondikemarlen
Copy link
Author

After much digging, I found a definition of max, but I don't know if it is the only definition https://github.com/lodash/lodash/blob/4.0.1-npm-packages/lodash.max/index.js

@klondikemarlen
Copy link
Author

klondikemarlen commented Nov 30, 2023

Some kind of overload like

function max(array: []): undefined;
function max(array: number[]): number;
function max(array: number[]): number | undefined {
  return (array && array.length)
    ? baseExtremum(array, identity, baseGt)
    : undefined;
}

const foo = max([4, 2, 8, 6]) // is number
const bar = max([]) // is undefined

might work?

@klondikemarlen
Copy link
Author

Or something like this?

type NonEmptyArray<T> = [T, ...T[]];

function max<T>(array: NonEmptyArray<T>): T;
function max<T>(array: T[]): T | undefined;
function max<T>(array: T[]): T | undefined {
  return (array && array.length)
    ? baseExtremum(array, identity, baseGt)
    : undefined;
}

const foo = max([4, 2, 8, 6]) // number
const bar = max([]) // undefined
const baz = max([[]]) // never[] - I don't even know what that means ...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

No branches or pull requests

1 participant