Neglecting the error message for type assignment in the Typescript compiler

Presented here is a scenario I am facing:

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

customerViewModel = customer;

Despite both Customer and CustomerLayoutViewModel being identical at the moment, there is no error generated upon compilation. This behavior is concerning to me because as time progresses, the types may diverge.

The main issue is that when the types do differ, I would like the code in question to trigger a compile error.

My question then becomes: How can I configure the compiler to highlight an error in the above example?

Answer №1

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

Answer №2

There won't be a compile error in this scenario since the types customer and customerViewModel are not specified. However, if you attempt something like the following, a compile time error will occur:

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

customerViewModel  = customer;

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How to use jQuery to locate and update the final parameter of a URL

Hello everyone, I've already done some research but couldn't find a solution that fits my needs. Can anyone assist me with this? I currently have a URL "/view/album/4/photo/1" and I am looking to remove the final parameter and replace it with so ...

"Enjoy a unique browsing experience with a two-panel layout featuring a fixed right panel that appears after scrolling

I am facing difficulty in designing a layout with two panels where the left panel has relative positioning and the right panel becomes fixed only after a specific scroll point. Additionally, I need the height of the right panel to adjust when the page scro ...

The fs.fsync(fd, callback) function in the node.js API allows you

Can you explain the purpose of fs.fsync(fd, callback) in the Node.js API? fs.fsync(fd, callback) This function is used for asynchronous fsync(2). The completion callback only returns an exception if there is one. fs.fsyncSync(fd) This function is for ...

Honing in on JavaScript Media Queries within React

I have been attempting to incorporate the media query concept from a resource I found here in my React project. However, when testing the code snippet below, I encountered the following error: TypeError: isMobile.addListener is not a function function App ...

What issue are we encountering with those `if` statements?

I am facing an issue with my Angular component code. Here is the code snippet: i=18; onScrollDown(evt:any) { setTimeout(()=>{ console.log(this.i) this.api.getApi().subscribe(({tool,beuty}) => { if (evt.index == ...

Leveraging React Native to retrieve information from a promise in JSON format

After successfully fetching the JSON data, I now have an array. My question is how can I utilize the elements within this array in a React Native environment? Below is my current approach: export default function display() { const fetching = async() => ...

Tips for hiding a soft keyboard with jQuery

Here is a text button: <input type="text" class="field" id="something" name="something" placeholder="text" autofocus /> I want to prevent the android soft keyboard from popping up and keep the focus on this field. I only want to do this for this ...

Is it possible to update the state of an array within a .then() function in React?

` After retrieving an array of points with city and state information, I attempted to convert these points to latitude and longitude by making a fetch call. However, upon trying to update the state of the newly generated array, I found that it remained ...

Container struggling to contain overflowing grid content items

While creating a grid in nextjs and CSS, I encountered an issue. Whenever I use the following code: display: grid; The items overflow beyond the container, even though I have set a maximum width. Instead of flowing over to the next row, the items just kee ...

Is it possible for me to convert my .ejs file to .html in order to make it compatible with Node.js and Express?

I have an index.html file and I wanted to link it to a twitter.ejs page. Unfortunately, my attempts were unsuccessful, and now I am considering changing the extension from ejs to html. However, this approach did not work either. Do .ejs files only work wit ...

The cascade option in TypeORM entities

In my project, I am working with two entities named Order and Address, which are connected through a @ManyToMany relationship. For the Address entity: @ManyToMany(() => Order, (order) => order.address, { cascade: true }) @JoinTable() order: Order; ...

Send an object to query when using Router.push in Next.js

Just getting started with NextJs and I'm experimenting with passing an object to another page through a component. Let me show you the code and explain what I'm attempting to accomplish: The object I want to pass looks like this: objectEx = { ...

Requirements for generating random numbers in JavaScript. Can anyone help me understand how to implement this requirement effectively?

I've been experimenting with JavaScript to create a blackjack game, but I'm having trouble getting my code to work properly. My goal is for the getRandomCard() function to generate numbers between 1 and 13. Specifically, I want it to return 11 wh ...

Executing a JavaScript/jQuery function on the following page

I'm currently working on developing an internal jobs management workflow and I'd like to enhance the user experience by triggering a JavaScript function when redirecting them to a new page after submitting a form. At the moment, I am adding the ...

Dynamic options can now be accessed and modified using newly computed getters and setters

When using Vuex with Vue components, handling static fields that are editable is easily done through computed properties: computed: { text: { get() { return ... }, set(value) { this.$store.commit... }, }, }, <input type ...

Problem with Vue.js dropdown functionality in Internet Explorer

After developing a form using Vue.js to allow users to save and return to their answers, I encountered an issue in Internet Explorer. When the page loads, the dropdown menu tied to a computed property does not display the previously selected answer as expe ...

Storing keys and multiple maps with React applications

Having a multiple array with an option set created, everything is functioning correctly const groups1 = OrgServices.reduce((all, cur) => ((all[cur.grouptype] ??= []).push(...cur.servicetype), all), {}); const output1 = Object.entries(groups1).map ...

Using Rxjs to dynamically map values from an array with forkJoin

Greetings! I have a collection of Boolean observables and would like to apply a logical AND operation. Currently, I am passing static values 'a' and 'b', but I am unsure of the number of elements in the totalKeys array. import { forkJoi ...

How can I make the droppable elements only drop within draggable elements in jQuery UI?

After reading several similar articles and questions, I am still struggling to get this working properly when there are multiple droppable elements with the same named class. Is there a way to ensure that the dragged element can only be dropped in a speci ...

Issue: Node Sass 8.0.0 is not compatible with the version ^4.0.0

I encountered an error when starting a React app with npm start. How can I resolve this issue? ./src/App.scss (./node_modules/css-loader/dist/cjs.js??ref--6-oneOf-5-1!./node_modules/postcss-loader/src??postcss!./node_modules/resolve-url-loader??ref--6-oneO ...