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

feat(array): narrow return type for first and last #140

Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions src/array/first.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,11 @@
* // 0
* ```
*/
export function first<T>(array: readonly T[]): T | undefined
export function first(array: readonly []): undefined
export function first<T>(array: readonly T[]): T
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can't assume the length of the array type is not zero here, so return type has to be T | undefined. Or is your goal to align this with arr[0]-style access?

Copy link
Contributor

@MarlonPassos-git MarlonPassos-git Jul 28, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's the same case as #139 (comment)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed, invalid for similar reasons. Suggest closing.


export function first<T, U>(array: readonly T[], defaultValue: U): T | U
export function first<U>(array: readonly [], defaultValue: U): U
export function first<T, U>(array: readonly T[], defaultValue: U): T

export function first(array: readonly unknown[], defaultValue?: unknown) {
return array?.length > 0 ? array[0] : defaultValue
Expand Down
6 changes: 4 additions & 2 deletions src/array/last.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,11 @@
* // 0
* ```
*/
export function last<T>(array: readonly T[]): T | undefined
export function last(array: readonly []): undefined
export function last<T>(array: readonly T[]): T

export function last<T, U>(array: readonly T[], defaultValue: U): T | U
export function last<U>(array: readonly [], defaultValue: U): U
export function last<T, U>(array: readonly T[], defaultValue: U): T

export function last(array: readonly unknown[], defaultValue?: unknown) {
return array?.length > 0 ? array[array.length - 1] : defaultValue
Expand Down
Loading