Skip to content

Add NonEmptyArray to lib (but **not** length > 0 narrowing) #60491

@Rudxain

Description

@Rudxain

⚙ Compilation target

ES2023

⚙ Library

ES2023

Missing / Incorrect Definition

type NonEmptyArray<T> = [T, ...T[]]
type ReadonlyNonEmptyArray<T> = readonly [T, ...readonly T[]]

Sample Code

const is_non_empty = <T>(a: ReadonlyArray<T>): a is ReadonlyNonEmptyArray<T> =>
	a.length > 0

function sum(a: ReadonlyNonEmptyArray<number>): number
function sum(a: ReadonlyNonEmptyArray<bigint>): bigint
function sum(a:
	ReadonlyNonEmptyArray<number> |
	ReadonlyNonEmptyArray<bigint>
) {
	//@ts-expect-error
	return a.reduce((acc, x) => acc + x)
}

Documentation Link

There's no docs that I'm aware of. However, there are multiple issues using this boilerplate. See also: #60463

Here's a WIP example implementations of sum. The sample code is a simplified version of that. More info here

Metadata

Metadata

Assignees

No one assigned

    Labels

    Awaiting More FeedbackThis means we'd like to hear from more people who would be helped by this featureSuggestionAn idea for TypeScript

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions