How to declare a type that allows null or undefined in TypeScript?
Hi! I just started learning TypeScript and ran into a problem. I have a function that should accept a number, but sometimes I want to pass null or just not pass anything (undefined). In regular JavaScript this works fine, but TypeScript complains.
Here's an example of my code:
```typescript
function greetUser(age: number) {
console.log(`Age: ${age}`);
}
// Want to pass null if age is unknown
greetUser(null); // Error: Argument of type 'null' is not assignable to parameter of type 'number'.
// Or not pass the argument at all
greetUser(); // Error: Expected 1 arguments, but got 0.
```
I tried using `age: number | null`, but then the function doesn't allow passing undefined. And if I write `age: number | undefined`, it doesn't work with null.
No answers yet.
Log in to leave an answer
Blogs