Objects & Interfaces
Object Type Annotations
Master inline object type annotations, property type rules, excess property checks, structural typing, and difference between object, Object, and Record in TypeScript.
Objects are the primary data structures in JavaScript applications. In TypeScript, Object Type Annotations allow you to define the exact shape of an object, specifying the names and types of its properties and methods.
1. Inline Object Annotations
You can annotate an object type inline by listing its property names and corresponding types separated by semicolons or commas:
2. Structural Typing (Duck Typing)
TypeScript uses a Structural Type System. Two object types are compatible if they share the same structure, regardless of how or where they were defined.
3. Excess Property Checks
When passing an object literal directly into a function or variable assignment, TypeScript performs Excess Property Checking to flag accidental typos.
4. object vs Object vs {} in TypeScript
TypeScript has three distinct types related to objects:
1. object (Lowercased): Represents any non-primitive type (objects, arrays, functions, dates). Primitive values (number, string, boolean) are rejected.
2. Object (Capitalized): Represents instances of JavaScript's Object class. Accepts any value except null and undefined.
3. {} (Empty Object): Represents any non-nullish value (all primitives except null and undefined).
5. Interactive Code Playground
Test object type annotations below:
6. Common Pitfalls & Edge Cases
Object or {} Instead of Specific Interfaces: Declaring variables as Object or {} provides almost no property autocomplete or type safety. Always specify explicit property keys.7. Summary Comparison Table
| Type | Allows Primitives? | Allows Arrays / Functions? | Recommended Purpose |
|---|---|---|---|
{ x: number } | No | No | Specific object shape contract |
object | No | Yes | Non-primitive values (Object.create(obj)) |
Object / {} | Yes (Except null/undefined) | Yes | Almost never recommended |