I have the following scenario:
const customer = new Customer();
let customerViewModel = new CustomerLayoutViewModel();
customerViewModel = customer;
This does not produce an error when compiled which in my mind is the wrong behaviour. This seems to be due to the fact that Customer
and CustomerLayoutViewModel
are completely identical.
The problem is that over time they will not be identical and I want the above code to give a compile error because the types are different.
So my question: How do I configure the compiler to produce an error in the above example?
Typescript uses structural typing when determining type compatibility. This means that if the two types have a compatible structure they will be compatible:
class Customer { name: string }
class CustomerLayoutViewModel { name: string }
const customer = new Customer();
let customerViewModel = new CustomerLayoutViewModel();
customerViewModel = customer; // OK compatible
If Customer
has extra properties the types are still compatible, there is no chance someone will access through customerViewModel
something that isn't there:
class Customer { name: string; fullName: string }
class CustomerLayoutViewModel { name: string }
const customer = new Customer();
let customerViewModel = new CustomerLayoutViewModel();
customerViewModel = customer; // still OK compatible
You will get compatibility errors if CustomerLayoutViewModel
has extra required properties:
class Customer { name: string }
class CustomerLayoutViewModel { name: string; fullName: string }
const customer = new Customer();
let customerViewModel = new CustomerLayoutViewModel();
customerViewModel = customer; //error now
The one way to ensure types are incompatible it to add a private field to a class. private fields will not be compatible with any other field in any other class event if the name is the same:
class Customer { private x: string }
class CustomerLayoutViewModel { private x: string }
const customer = new Customer();
let customerViewModel = new CustomerLayoutViewModel();
customerViewModel = customer; //error Types have separate declarations of a private property 'x'.