How to create an object based on a TypeScript interface? Correct ways
Hello everyone! I recently started learning TypeScript and ran into a problem. I have an interface for describing a user:
```typescript
interface User {
id: number;
name: string;
email: string;
age?: number;
}
```
Now I want to create an object that matches this interface. I tried doing this:
```typescript
const user: User = {
id: 1,
name: 'Ivan',
email: 'ivan@example.com'
};
```
This works, but if I try to create an empty object and then add fields, TypeScript complains:
```typescript
const user: User = {};
user.id = 1;
user.name = 'Ivan';
// Error: Type '{}' is not assignable to type 'User'.
```
I also saw that you can use `as` for type casting, but I read that it's dangerous. Please advise how to correctly create
No answers yet.
Log in to leave an answer