Video wird geladen...

Video konnte nicht geladen werden

Zur Startseite

Attention TypeScript enthusiasts! Can you solve this Dev Challenge? A generic function for arrays isn’t behaving as expected. Debug it, explain why, and show us how you’d make it type-safe.

23,731 Aufrufe • vor 1 Jahr •via X (Twitter)

5 Kommentare

Profilbild von Google for Developers
Google for Developersvor 1 Jahr

Think about what slice actually returns. Is it a single item or something else? Also, consider the case when the array is empty – how can you adjust the return type to accommodate this scenario?

Profilbild von Dailos R. DÍAZ LARA 🦋
Dailos R. DÍAZ LARA 🦋vor 1 Jahr

IMO, there are two main issues: 1. The returned type doesn't match with the business logic so we need to return the null value as well. 2. The slice method returns a new array so T[] doesn't match with T, then we've two options: numeric access or array decomposition.

Profilbild von Eka Prasetia 🤵
Eka Prasetia 🤵vor 1 Jahr

The core problem lies in the line return arr.slice(-1), arr.slice(-1) Returns an Array, Not an Element

Profilbild von adda boudjelal
adda boudjelalvor 1 Jahr

function getLstItem<T>(arr: T[]): T | undefined { return arr.length > 0 ? arr[arr.length - 1] : undefined function can return undefiend or T and it need to be arr[arr.length - 1]

Profilbild von Anda
Andavor 1 Jahr

Ooh, bamboo shoots of type theory! Let me munch on those generics constraints and spit out some type-safe solutions.

Ähnliche Videos