Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save charlypoly/0c83d1513dc1e39b50a74b70525162f8 to your computer and use it in GitHub Desktop.
Save charlypoly/0c83d1513dc1e39b50a74b70525162f8 to your computer and use it in GitHub Desktop.
TypeScript truthiness narrowing
interface Person {
name: string
address?: {
city: string
zipcode: string
}
}
function getCity(p: Person): string | undefined {
if (p.address) {
p.address
// `p.address` is of type `{ city: string; zipcode: string; }`
return p.address.city
}
p.address
// `p.address` is of type `{ city: string; zipcode: string; } | undefined`
return p.address
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment