Typescript employs structural typing to determine type compatibility. This means that if two types have a similar structure, they will be considered compatible:
class Customer { name: string }
class CustomerLayoutViewModel { name: string }
const customer = new Customer();
let customerViewModel = new CustomerLayoutViewModel();
customerViewModel = customer; // This is acceptable as they are compatible types
If Customer
has additional properties, the types remain compatible. This ensures that accessing something that does not exist through customerViewModel
is prevented:
class Customer { name: string; fullName: string }
class CustomerLayoutViewModel { name: string }
const customer = new Customer();
let customerViewModel = new CustomerLayoutViewModel();
customerViewModel = customer; // Compatibility is still maintained
Compatibility errors will arise if CustomerLayoutViewModel
contains extra necessary properties:
class Customer { name: string }
class CustomerLayoutViewModel { name: string; fullName: string }
const customer = new Customer();
let customerViewModel = new CustomerLayoutViewModel();
customerViewModel = customer; // Error occurs due to type incompatibility
The inclusion of a private field in a class is one way to ensure types are incompatible. Private fields are not compatible with any other fields in different classes, even if they share the same name:
class Customer { private x: string }
class CustomerLayoutViewModel { private x: string }
const customer = new Customer();
let customerViewModel = new CustomerLayoutViewModel();
customerViewModel = customer; // Error is thrown as private properties have separate declarations