How to declare a nullable type in TypeScript?
Hi! I just started learning TypeScript and ran into a problem. I'm writing a small task management application. I have an interface for a task, where the `completedAt` field should be `Date` if the task is completed, or `null` if it's not yet completed. Also there is an `assignee` field that can be a string with the assignee's name or absent (`null`/`undefined`).
Here's how I tried to describe it:
```typescript
interface Task {
id: number;
title: string;
completedAt: Date;
assignee: string;
}
```
But TypeScript complains when I try to assign `null` to the `completedAt` field:
```typescript
const task: Task = {
id: 1,
title: "Buy groceries",
completedAt: null, // Error: Type 'null' is not assignable to type 'Date'.
assignee: null // Error: Type 'n
No answers yet.
Log in to leave an answer
Blogs