Concepts

Partial Type Assertions in TypeScript

Summary

In TypeScript, you can create a variable that references an entire object but only “sees” specific properties for type checking purposes.

The actual object remains unchanged with all its properties, but TypeScript will only allow access to the properties defined in the type assertion through that variable.

This is useful when you want to work with a subset of properties from a larger object.

Example:

// EXAMPLE 1: Basic Concept
interface FullPerson {
    name: string;
    age: number;
    address: string;
    ssn: string;
    bankDetails: object;
}
 
// Create an object with all properties
const person: FullPerson = {
    name: "John",
    age: 30,
    address: "123 Main St",
    ssn: "123-45-6789",
    bankDetails: { account: "12345" }
}
 
// Create a "view" that only cares about public info
const publicView = person as { name: string, age: number }
 
// TypeScript only allows access to specified properties
publicView.name  // ✅ OK
publicView.age   // ✅ OK
publicView.ssn   // ❌ TypeScript Error: Property 'ssn' does not exist
 
// But the actual object still has all properties
console.log(publicView)  // Shows all properties!
 
// EXAMPLE 2: Real-world Use Case
// Common use case: working with a subset of global object properties
const globalWithDb = global as unknown as { 
    database: DatabaseClient | undefined 
}
 
// TypeScript only knows about database property
globalWithDb.database        // ✅ OK
globalWithDb.setTimeout     // ❌ TypeScript Error
 
// But global object remains unchanged with all Node.js properties
console.log(globalWithDb)   // Shows all global object properties

Key Takeaways

  1. Original object remains unchanged
  2. Type assertion only affects TypeScript’s type checking
  3. Only specified properties will be accessible through the new variable
  4. Useful for working with specific parts of large objects
  5. Commonly used with global objects or when dealing with subsets of data

This pattern is particularly useful when:

  • Working with large global objects
  • Creating restricted views of data
  • Handling subset of properties from larger interfaces
  • Managing type safety for specific use cases