Concept Flow - Object type annotation inline
Start
Declare variable with inline object type
Assign object matching type
Use variable
End
This flow shows how to declare a variable with an inline object type, assign a matching object, and then use it.
const person: { name: string; age: number } = { name: "Alice", age: 30 }; console.log(person.name); console.log(person.age);
| Step | Action | Evaluation | Result |
|---|---|---|---|
| 1 | Declare 'person' with inline type {name: string; age: number} | TypeScript checks type | Variable 'person' ready to hold matching object |
| 2 | Assign {name: "Alice", age: 30} to 'person' | Check object matches type | Assignment successful |
| 3 | Access 'person.name' | Retrieve value | "Alice" |
| 4 | Access 'person.age' | Retrieve value | 30 |
| 5 | End of code | No more actions | Program ends |
| Variable | Start | After Assignment | Final |
|---|---|---|---|
| person | undefined | {name: "Alice", age: 30} | {name: "Alice", age: 30} |
Inline object type annotation syntax:
const varName: { prop1: type1; prop2: type2 } = { prop1: value1, prop2: value2 };
- Defines object shape directly where variable is declared
- TypeScript checks assigned object matches this shape
- Access properties safely with autocomplete and type checkslet user: { name: string; age: number };{ name: string; age: number } tells TypeScript that user must have a string name and a number age.{ id: number; title: string }.function printUser(user: { name: string; age: number }) {
console.log(`${user.name} is ${user.age} years old.`);
}
printUser({ name: 'Alice', age: 30 });name as string and age as number.{ name: 'Alice', age: 30 } matches the expected type exactly.let product: { id: number; name: string } = { id: 101, name: 'Pen', price: 5 };id and name properties.price which is not declared in the type, causing an error.title and an optional number year. Which inline type annotation is correct?? after the property name.year as optional with year?: number. Other options either make title optional or use incorrect types.Pass the test and this pattern moves unknown