← Alle AufgabenTypeScript · Junior

Generics: first und last

Die Funktionen first(items) und last(items) liefern das erste und das letzte Element eines Arrays. Im Moment nehmen und liefern sie any, das Ergebnis verliert also seinen Typ.

Mach sie generisch: für ein number[] soll das Ergebnis number | undefined sein, für ein Array mit as const eine Union seiner Literale. Ein leeres Array ergibt undefined.

Tests (6)

Typtests prüft der TypeScript-Compiler im strict-Modus. Expect<Equal<A, B>> besteht, wenn die Typen exakt gleich sind, und // @ts-expect-error, wenn die nächste Zeile nicht kompiliert. Der erste Start lädt den Compiler und dauert daher ein paar Sekunden.

  1. Typen
    const n = first([1, 2, 3]);
    type _ = Expect<Equal<typeof n, number | undefined>>;
  2. Typen
    const s = last(['a', 'b'] as const);
    type _ = Expect<Equal<typeof s, 'a' | 'b' | undefined>>;
  3. Typen
    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');