Video wird geladen...
Video konnte nicht geladen werden
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

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?

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.

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

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]

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