What is the reason behind TypeScript permitting the assignment of a class instance to a variable that is of a different type?

When examining the given code, it raises a question about why the TypeScript compiler permits the assignment const c1: I = new C();. The issue arises when the function call c1.z(args); results in an error due to the absence of the first property in the args object. Shouldn't the compiler identify that an instance of the C class is incompatible with the I interface since the z function in C requires an argument with the first property?

interface CArgs {
    first: number;
    second: number;
}

interface IArgs {
    second: number;
}

class C {
    z(args: CArgs) {
        args.first.toString();
    }
}

interface I {
    z(args: IArgs): void;
}

const args = {
    second: 2
};

const c1: I = new C();
c1.z(args);

Answer №1

To resolve this issue, simply replace the method with a property as an arrow function:

interface CArgs {
  first: number;
  second: number;
}

interface IArgs {
  second: number;
}

class C {
  z(args: CArgs) {
    args.first.toString();
  }
}

interface I {
  z: (args: IArgs) => void; // modification
}

const args = {
  second: 2
};

const c1: I = new C();
c1.z(args);

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

A guide on implementing TypeScript with React Native's platform-specific extensions

The issue at hand: In my react native project, I am using a custom hook that has platform-specific code. I need to import this hook based on the platform in use. When I import it as import useWifi from 'hooks/use-wifi.android';, everything works ...

Angular 2: Obtaining the caret position in a contenteditable 'div'

Take a look at this code snippet: <div #test (click)="onClick(test)" contenteditable="true"> This text can be edited by the user. </div> @ViewChild('test') el:ElementRef; constructor(private elementRef: ElementRef) {} ...

Tips for integrating Reactjs with Chessboard.js

Recently, I stumbled upon chessboardjs (https://chessboardjs.com/) as a way to hone my React coding skills. However, I hit a roadblock while trying to implement a simple example of displaying the chess board in my application. The documentation instructed ...

What is the reason for recursion not producing a new object as output?

Trying to filter out nodes in a recursion function that iterates through a tree based on the registry property. function reduceNodesRegistry(source: any) { if (!source.registry) return source; return { ...source, children: s ...

Guide to specifying an explicit return type annotation for a recursive closure with JSDoc

In a project that utilizes vanilla JavaScript and type checking with tsc through JSDoc annotations, I have encountered a challenging use case. There is a function that returns another function, which may recursively call itself while also reassigning certa ...

Unable to locate the Chart object within the chartjs-plugin-labels.js file

Hello there, I am currently working on an Angular project where I want to incorporate a chart plugin. To achieve this, I executed the following commands: npm install angular2-chartjs npm install chartjs-plugin-labels Following that, I imported it into my ...

What is the reason that Ionic Lifecycle hooks (such as ionViewWillEnter and ionViewWillLeave) do not trigger when utilized as an HTML Selector?

I have a project using Angular along with Ionic 4. I encountered an issue where the Ionic Lifecycle Hooks in the child page do not fire when it is called from the parent page's HTML using the HTML Selector. Why does this happen? How can I properly ut ...

Populating datasets with relative indexing

I am working on a code where I need to fill the datasets with the property isProjected set to 1. There are 3 datasets - lower estimate, projected, and upper estimate. The goal is to fill the Lower Estimate and Upper Estimate with a background color of rgba ...

I have encountered TS 2322 error in a TypeScript code written in React

import { AdapterDayjs } from '@mui/x-date-pickers/AdapterDayjs'; import { LocalizationProvider } from '@mui/x-date-pickers/LocalizationProvider'; import { DatePicker } from '@mui/x-date-pickers/DatePicker'; const StyledTextFi ...

Issue encountered while attempting to utilize the useRef function on a webpage

Is it possible to use the useRef() and componentDidMount() in combination to automatically focus on an input field when a page loads? Below is the code snippet for the page: import React, { Component, useState, useEffect } from "react"; import st ...

Guide to displaying an input box depending on the selection made in a Mat-Select component

I am working on a mat-select component that offers two options: Individual Customers and Organizational Customers. When selecting Individual Customers, the dropdown should display three options: First Name, Last Name, and Customer Id. However, when choosin ...

Troubleshooting compatibility issues between Sailsjs Services and TypeScript in Vscode

Having an issue with TypeScript in a Sails.js application. I am utilizing TypeScript to write my controller and attempting to use Sails.js services within the controllers. However, I encounter a syntax error in VSCODE. Below is the code snippet from MyCo ...

Error: The template is unable to parse due to unrecognized element 'mat-label'

When attempting to write about the datepicker, I encountered the following error: Uncaught Error: Template parse errors: 'mat-label' is not a recognized element: If 'mat-label' is an Angular component, please ensure that it is part o ...

Angular 2 - Error: Regular expression missing forward slash syntax

Recently, I began working on an Angular 2 tutorial app using this repository. While I can successfully launch the app and display static content, I am facing challenges with rendering dynamic content from the component. I have a feeling that the error migh ...

Is it feasible to verify the accuracy of the return type of a generic function in Typescript?

Is there a way to validate the result of JSON.parse for different possible types? In the APIs I'm working on, various Json fields from the database need to have specific structures. I want to check if a certain JsonValue returned from the database is ...

Reusing a lazy-loaded module across multiple applications

Currently, I am working on an enterprise Angular 2 application with numerous lazy loaded modules. A new project came up where I needed to reuse a module that was previously created for the main app. After researching online, the only solution I found was ...

Why won't Angular 4 create the node_modules folder when using ng new to initialize a new project?

Recently reinstalled Angular and began a new project using ng new. However, I encountered issues when trying to run ng serve after creating the project and changing into its directory. On my Mac Mini, I can simply navigate to the project folder and run ng ...

What steps do I need to take to export my TypeScript declarations to an NPM package?

I have multiple repositories that share similar functionality. I want to export type declarations to an NPM package so I can easily install and use them in my projects. Within the root directory, there is a folder called /declarations, containing several ...

Sorting complex strings in Typescript based on the dates contained within them

How can I sort a list of 2 strings with dates inside them so that the earlier one always comes first? The date is always after the second comma. For example, const example = ["AAA,5,2020-09-17T21:14:09.0545516Z", "AAA,0,2020-09-03T20:38:08. ...

Converting HTML templates into AMD modules using grunt-ts

When using the grunt-ts plugin and specifying the html: ["*.tpl.html"] option, it converts *.tpl.html files into *.tpl.html.js files at the end of the process, creating a global var. Is there a way to configure grunt-ts to output the final .js file in a d ...