When implementing a TypeScript interface, there is no method parameter checking performed

interface IConverter {
    convert(value: number): string
}

class Converter implements IConverter {
    convert(): string { // no error?
        return '';
    }
}

const v1: IConverter = new Converter();
const v2: Converter = new Converter();

v1.convert(); // error, convert has parameter, although Converter's convert doesn't expect one
v2.convert(); // ok, convert has no parameters, although Converter implements IConverter which should have a parameter

Converter is supposed to implement IConverter, which includes a method that expects one parameter. However, in the definition of Converter, this parameter is missing. It is intriguing why TypeScript compiler does not flag this discrepancy as an error when implementing interfaces.

Answer №1

Structural typing is a key feature of Typescript that determines type compatibility, especially when it comes to functions. Unlike some other programming languages, Typescript allows for flexibility in function signatures - meaning the declaration and implementation don't have to match exactly as long as they are deemed safe by the compiler.

Essentially, this means that a function with fewer parameters can serve as an implementation for a function declaration with more parameters. This is possible because any extra arguments passed in will simply be ignored by the implementation, thus avoiding runtime errors in most cases (though there may be exceptions in certain scenarios).

The reason you encounter an error with v1 but not with v2 is due to how the compiler treats variable types post-assignment. Once assigned, the compiler only looks at the current type of the variable, not what was originally assigned to it. Therefore, in the case of v1, the compiler sees that IConverter.convert expects a parameter, while in the case of v2, it recognizes that Converter.convert requires no arguments.

Answer №2

In TypeScript, a function with fewer parameters can be considered as a function type with more parameters because the additional parameters will simply be overlooked during runtime. For more information on this topic, check out the TypeScript handbook.

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

Performing DTO validation in the controller before passing data to the service

My current challenge involves implementing validation in a PUT request to update data stored in MongoDB: DTO: export enum reportFields { 'startDate', 'targetDateOfCompletion', 'duration', } export class updateS ...

Modifying the version target of TypeScript code results in the TypeScript Compiler being unable to locate the module

After installing signalr via npm in Visual Studio 2019, I encountered an issue. When the target in my compiler options is set to ES6, I receive the error TS2307 (TS) Cannot find module '@microsoft/signalr.'. However, when I change the target to E ...

React hooks causing dynamic object to be erroneously converted into NaN values

My database retrieves data from a time series, indicating the milliseconds an object spends in various states within an hour. The format of the data is as follows: { id: mejfa24191@$kr, timestamp: 2023-07-25T12:51:24.000Z, // This field is dynamic ...

"Exploring the process of creating a custom type by incorporating changes to an existing interface

One of the challenges I'm facing is defining an object based on a specific interface structure. The interface I have looks like this: interface Store { ReducerFoo : ReducerFooState; ReducerBar : ReducerBarState; ReducerTest : ReducerTestSt ...

Navigating in Angular with parameters without modifying the URL address

In a nutshell, my goal is to navigate to a page with parameters without showing them in the URL. I have two components: Component A and B. What I want to do is route to B while still needing some parameters from A. I know I can achieve this by setting a ...

The type 'typeof globalThis' does not have an index signature, therefore the element is implicitly of type 'any'. Error code: ts(7017) in TypeScript

I'm encountering an issue with my input handleChange function. Specifically, I am receiving the following error message: Element implicitly has an 'any' type because type 'typeof globalThis' has no index signature.ts(7017) when att ...

Is there an equivalent concept to Java's `Class<T>` in TypeScript which allows extracting the type of a class constructor?

I'm in need of a feature similar to the Class functionality in Java, but I've had no luck finding it. Class<T> is exactly what I require. I believe it could be named NewableFunction<T>. However, such an option does not exist. Using M ...

Having trouble with the environment.ts file during Angular 2 testing

Having issues while attempting to write a basic test in Angular 2, specifically with an error related to environment.ts: ERROR in ./web/environments/environment.ts Module build failed: Error: web\environments\environment.ts is missing from ...

The outcome of data binding is the creation of a connected data object

I am attempting to link the rows' data to my view. Here is the backend code I am using: [Route("GetCarCount")] [HttpGet] public async Task<long> Count() { return await _context.Cars.CountAsync(); } ...

Adding attributes to parent DOM elements of a component in Angular2: A Step-by-Step Guide

I'm working with the following code: ... <div class="container"> <div class="fancy"> <fancybutton></fancybutton> </div> <button (click)="addAttribute()">Remove</button> <button (click)="remAttr ...

Transitioning React components organized in groups to TypeScript

As I transition my react project to incorporate typescript, one challenge I encountered was adjusting the file structure. In its simplified form, here is how the original js project's file structure looked like: src components index.js inputs butt ...

What is the process for defining the type of the context for an Apollo resolver?

I am facing an issue with my Apollo GraphQL subgraph where I need to define the type for the context argument in my resolvers. When creating a resolver, I tried setting the context type like this: interface Context { dataSources: { shopify: Shopify; ...

Is there a way to make the vss sdk treeview collapse automatically?

Is there a way to have the nodes of a combo control of type TreeView.ComboTreeBehaviorName collapsed by default? I've searched through the documentation at this link and this link, but couldn't find a solution. I also examined the types in vss. ...

Error: Import statement is invalid outside of a module in next.js

Every time I attempt to run the register.tsx page in my next.js project, I encounter the error message shown below. My Next.Js project utilizes TypeScript. import React, { useState } from 'react'; ^^^^^^ SyntaxError: Cannot use import st ...

When using @testing-library/react (rtl), the 'waitFor' function achieves success even without the need for the 'await' keyword

waitFor() is causing my test to fail while waitFor() (without await) makes it pass. The official documentation states: Async methods return a Promise, so you must always use await or .then(done) when calling them. (https://testing-library.com/docs/guide ...

Encountering difficulty when trying to initiate a new project using the Nest CLI

Currently, I am using a tutorial from here to assist me in creating a Nest project. To start off, I have successfully installed the Nest CLI by executing this command: npm i -g @nestjs/cli https://i.stack.imgur.com/3aVd1.png To confirm the installation, ...

Exploring TypeAhead functionality in Reactjs 18

I have encountered an issue while using react-bootstrap-typeahead version 5.1.8. The problem arises when I try to utilize the typeahead feature, as it displays an error related to 'name'. Below is my code snippet: import { Typeahead } from " ...

After updating from angular4 to angular 5, the npm test is failing with the error message "TypeScript compilation cannot find test.ts file"

After upgrading my app from Angular4 to Angular 5 using the steps provided on https://update.angular.io/, I encountered an issue. While I can successfully run ng-serve and ng build without any problems, the npm test command for ng test is failing with the ...

Tips for correctly decorating constructors in TypeScript

When a class is wrapped with a decorator, the superclasses lose access to that classes' properties. But why does this happen? I've got some code that demonstrates the issue: First, a decorator is created which replaces the constructor of a cla ...

Learn the steps to refresh a component in Angular 5

src/shared.service.ts public _testData:any;   set testData(value:any) {     this._testData = value   }   get testData():any {     return this._testData;   } src/header.component.ts private postValues( ...