TypeScript
/Beginner
Object Types
Definition
Defining the shape of a JavaScript object by specifying the names and types of its properties.
Explain Like I'm New
An Object Type is a blueprint. If you are building a 'User' object, the blueprint dictates that it MUST have a name that is a string, and an age that is a number. If you try to add 'wingspan', the inspector rejects it.
Real World Example
Typing a React Component's props object or the shape of a JSON response from an API.
Common Use Cases
- •Defining data structures
- •Type checking API responses
Interactive Example
// Inline object typing (Good for small objects) function printLocation(pt: { x: number; y: number }) { console.log(`The coordinates are X: ${pt.x}, Y: ${pt.y}`); } // Using a Type Alias (Better for reuse) type User = { id: number; name: string; }; const currentUser: User = { id: 1, name: "Alice" }; // ERROR: Object literal may only specify known properties // const badUser: User = { id: 2, name: "Bob", admin: true };
Interview Questions
basic
- How do you define the type of an object directly inline?
intermediate
- What is excess property checking?
advanced
- What is the difference between `{}` and `object` and `Object`?