Determining object type when creating a literal in TypeScript
Hi everyone! I recently started learning TypeScript and encountered a problem that seems strange to me. When I create an object using a literal, I want to explicitly specify its type, but I don't understand how to do it correctly.
Here's an example: I have a `User` interface, and I want to create a `user` object with this type. I tried several approaches, but I'm not sure which one is correct and what the difference is.
```typescript
interface User {
name: string;
age: number;
}
// Method 1: type annotation after declaration
const user1: User = {
name: 'Alexey',
age: 30
};
// Method 2: type assertion
const user2 = {
name: 'Maria',
age: 25
} as User;
// Method 3: without type
const user3 = {
name: 'Ivan',
age: 35
};
```
Questions:
1. What is the difference between these approaches?
2. Which
No answers yet.
Log in to leave an answer