← 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.
Ctrl+Enter runs the tests. Tab indents; to leave the editor with the keyboard, press Esc and then Tab. Your code is saved in this browser.
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.
- types
const n = first([1, 2, 3]); type _ = Expect<Equal<typeof n, number | undefined>>;
- types
const s = last(['a', 'b'] as const); type _ = Expect<Equal<typeof s, 'a' | 'b' | undefined>>;
- types
const e = first([] as string[]); type _ = Expect<Equal<typeof e, string | undefined>>;
expect(first([1, 2, 3])).toBe(1); expect(last([1, 2, 3])).toBe(3);
expect(first([])).toBe(undefined); expect(last([])).toBe(undefined);
expect(last(['only'])).toBe('only');