Video yükleniyor...

Video Yüklenemedi

Ana Sayfaya Dön

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 görüntüleme • 1 yıl önce •via X (Twitter)

5 Yorum

Google for Developers profil fotoğrafı
Google for Developers1 yıl önce

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 🦋 profil fotoğrafı
Dailos R. DÍAZ LARA 🦋1 yıl önce

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 🤵 profil fotoğrafı
Eka Prasetia 🤵1 yıl önce

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

adda boudjelal profil fotoğrafı
adda boudjelal1 yıl önce

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 profil fotoğrafı
Anda1 yıl önce

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

Benzer Videolar