← All tasksTypeScript · Junior

Generics: first and last

The functions first(items) and last(items) return the first and the last element of an array. Right now they take and return any, so the result loses its type.

Make them generic: for a number[] the result should be number | undefined, and for an as const array a union of its literals. An empty array gives undefined.

Tests (6)

Type tests are checked by the TypeScript compiler in strict mode. Expect<Equal<A, B>> passes when the types match exactly, and // @ts-expect-error passes when the next line does not compile. The first run downloads the compiler, so it takes a few seconds.

  1. types
    const n = first([1, 2, 3]);
    type _ = Expect<Equal<typeof n, number | undefined>>;
  2. types
    const s = last(['a', 'b'] as const);
    type _ = Expect<Equal<typeof s, 'a' | 'b' | undefined>>;
  3. types
    const e = first([] as string[]);
    type _ = Expect<Equal<typeof e, string | undefined>>;
  4. expect(first([1, 2, 3])).toBe(1);
    expect(last([1, 2, 3])).toBe(3);
  5. expect(first([])).toBe(undefined);
    expect(last([])).toBe(undefined);
  6. expect(last(['only'])).toBe('only');