← Wszystkie zadaniaTypeScript · Junior

Generyki: first i last

Funkcje first(items) i last(items) zwracają pierwszy i ostatni element tablicy. Teraz przyjmują i zwracają any, więc wynik traci typ.

Zrób z nich generyki: dla number[] wynik ma być number | undefined, a dla tablicy as const unią jej literałów. Pusta tablica daje undefined.

Testy (6)

Testy typów sprawdza kompilator TypeScriptu w trybie strict. Expect<Equal<A, B>> przechodzi, gdy typy są dokładnie takie same, a // @ts-expect-error, gdy następna linia się nie kompiluje. Pierwsze uruchomienie pobiera kompilator, więc trwa kilka sekund.

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