How to simultaneously check for both null and undefined in TypeScript?
Hello, colleagues! I'm new to TypeScript and have encountered a problem that seems simple but is causing confusion. I need to write a check that filters out both `null` and `undefined`. In JavaScript, I'm used to just writing `if (value)`, but in TypeScript this is not always correct, since an empty string or 0 are also considered falsy values, and I could lose data.
Here's an example of my code:
```typescript
function processUser(user: { name: string | null | undefined; age?: number }) {
// How to correctly check that user.name is not null and not undefined?
if (user.name) {
console.log(user.name.toUpperCase()); // Works, but what if name = ""?
}
// I tried this:
if (user.name !== null && user.name !== undefined) {
console.log(user.name.length); // Works, but
No answers yet.
Log in to leave an answer
Blogs