return type not getting inferred correctly. what am i doing wrong here?

TS Playground - An online editor for exploring TypeScript and JavaS...
The Playground lets you write TypeScript or JavaScript online in a safe and sharable way.
16 Replies
nexxel
nexxelOP2y ago
type Person = {
name: string;
age?: number;
};

// should return array of numbers or undefined
const getAgesOfPersons = (persons: Person[]) => persons.map((person) => person.age)

// should return array of numbers but returns array of numbers of underfined
// is inference broken here?
const getAgesOfPersons2 = (persons: Person[]) => persons.map((person) => person.age).filter((age) => typeof age === "number")
type Person = {
name: string;
age?: number;
};

// should return array of numbers or undefined
const getAgesOfPersons = (persons: Person[]) => persons.map((person) => person.age)

// should return array of numbers but returns array of numbers of underfined
// is inference broken here?
const getAgesOfPersons2 = (persons: Person[]) => persons.map((person) => person.age).filter((age) => typeof age === "number")
Unknown User
Unknown User2y ago
Message Not Public
Sign In & Join Server To View
nexxel
nexxelOP2y ago
ah but shouldn't it change the type ideally?
Unknown User
Unknown User2y ago
Message Not Public
Sign In & Join Server To View
nexxel
nexxelOP2y ago
did not know about is thats quite cool
Unknown User
Unknown User2y ago
Message Not Public
Sign In & Join Server To View
nexxel
nexxelOP2y ago
Sadge
Unknown User
Unknown User2y ago
Message Not Public
Sign In & Join Server To View
nexxel
nexxelOP2y ago
thats nice, like a reusable type guard is there a library for such common type guards?
Unknown User
Unknown User2y ago
Message Not Public
Sign In & Join Server To View
nexxel
nexxelOP2y ago
makes sense
Unknown User
Unknown User2y ago
Message Not Public
Sign In & Join Server To View
nexxel
nexxelOP2y ago
thanks i'll give this a read thats pretty nice
Unknown User
Unknown User2y ago
Message Not Public
Sign In & Join Server To View
nexxel
nexxelOP2y ago
yeah probably there's no point in installing a lib for such small stuff
Unknown User
Unknown User2y ago
Message Not Public
Sign In & Join Server To View
Want results from more Discord servers?
Add your server