简体   繁体   中英

Typescript compiler type assignment error ignored

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?

This will not give compile error because you have not assigned the type of customer or customerViewModel , but if you do something like this then you should get compile time error:

const customer:Customer = new Customer();
let customerViewModel:CustomerLayoutViewModel = new CustomerLayoutViewModel();

customerViewModel  = customer;

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'. 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM