I stumbled upon this type declaration in my codebase which is meant for non-empty arrays:
type NonEmptyArray<T> = T[] & { 0: T }
and it functions as expected:
const okay: NonEmptyArray<number> = [1, 2];
const alsoOkay: NonEmptyArray<number> = [1];
const err: NonEmptyArray<number> = []; // error!
Queries:
1 I'm confused about the significance of
0
in{ 0: T }
. Can you please explain?2 What's the difference with the alternative declaration?
type NonEmptyArray<T> = [T, ...T[]];