How to declare an empty object with a type in TypeScript without compilation errors?
Hi! I recently started learning TypeScript and encountered a problem. I need to declare a variable with a specific type but initialize it with an empty object. Here's an example:
```typescript
interface User {
name: string;
age: number;
email: string;
}
const user: User = {}; // Error: Type '{}' is not assignable to type 'User'
```
The compiler complains that the empty object does not match the User interface. I understand that the empty object doesn't have the required fields name, age, and email. But I need the variable to be typed, and I will fill in the data later, for example, after an API request or during form processing.
I've tried these options:
- `const user = {} as User;` — works, but I've heard it's unsafe.
- `const user: Partial = {};` — also works, but
No answers yet.
Log in to leave an answer