Loading video...

Video Failed to Load

Go Home

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 views • 1 year ago •via X (Twitter)

5 Comments

Google for Developers's profile picture
Google for Developers1 year ago

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?

Dailos R. DÍAZ LARA 🦋's profile picture
Dailos R. DÍAZ LARA 🦋1 year ago

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.

Eka Prasetia 🤵's profile picture
Eka Prasetia 🤵1 year ago

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

adda boudjelal's profile picture
adda boudjelal1 year ago

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]

Anda's profile picture
Anda1 year ago

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

Related Videos