Created
November 29, 2021 10:50
-
-
Save charlypoly/0c83d1513dc1e39b50a74b70525162f8 to your computer and use it in GitHub Desktop.
TypeScript truthiness narrowing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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