Encountering unusual results while utilizing interfaces with overloaded arguments

I came across a situation where TypeScript allows calling a method with the wrong type of argument. Why doesn't the TypeScript compiler flag this as an issue?

interface IValue {
    add(value: IValue): IValue;
}

class NumberValue implements IValue {
    private readonly _rawNumber: number;

    public constructor(rawValue: number) {
        this._rawNumber = rawValue;
    }

    public add(value: NumberValue): NumberValue {
        const sum: number = this._rawNumber + value._rawNumber;
        return new NumberValue(sum);
    }
}

class StringValue implements IValue {
    private readonly _rawString: string;

    public constructor(rawValue: string) {
        this._rawString = rawValue;
    }

    public add(value: StringValue): StringValue {
        const sum: number = Number.parseFloat(this._rawString) + Number.parseFloat(value._rawString);
        return new StringValue(sum.toFixed());
    }
}

const v1: IValue = new NumberValue(42);
const v2: IValue = new StringValue("42");

// Unexpected behavior: No errors/warnings are shown. The method NumberValue#add() is called with an argument of type StringValue
const v3: IValue = v1.add(v2);

This is my tsconfig.json file:

{
    "compilerOptions": {
        "alwaysStrict": true,
        "declaration": true,
        "experimentalDecorators": true,
        "module": "commonjs",
        "moduleResolution": "node",
        "noImplicitAny": true,
        "target": "esnext",
        "strict": true,
        "strictNullChecks": true,
        "strictPropertyInitialization": true,
        "strictFunctionTypes": true
    }
}

I expected to receive a compilation error, but none were generated

Answer №1

If you want to create a user-friendly interface with the concept of polymorphic this in mind, consider utilizing the polymorphic this approach.

interface IValue {
    add(value: this): this;
}

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

Using Node.js with Typescript and RedisJSON allows for a powerful and efficient

I've recently started delving into nodejs, typescript, and redis for programming. However, I've encountered an issue with redis: when defining a data interface to be stored in redis, the system throws errors as soon as I try to specify the data t ...

I'm encountering a Typescript error where I'm unable to assign a function to RefObject.current and it's indicating that the function is not callable

Does anyone know why assigning a function type to a ref.current type is causing me issues? useEffect(() => { savedHandler.current = handler; // ERROR HERE: }, [handler]); TS2741: Property 'current' is missing in type '(e: Chang ...

Angular 2 select does not recognize the selected option

In my Angular 2 code, I am using ngFor to populate a dropdown with options. I want a specific option at a certain index to be selected by default. Currently, I tried using [attr.selected]="i == 0" but it ends up selecting the last option instead of the fi ...

A generic type in TypeScript that allows for partial types to be specified

My goal is to create a type that combines explicit properties with a generic type, where the explicit properties have priority in case of matching keys. I've tried implementing this but encountered an error on a specific line - can anyone clarify why ...

What techniques can be used to determine which exact key was matched by a generic?

I am trying to find a method to deduce a more general string type key from a specific string that can be associated with it. type Foo = { [x: `/tea/${string}/cup`]: void; [x: `/coffee/${string}/time`]: void; [x: `/cake/${string}/tin`]: void; } type ...

The JSON creation response is not meeting the expected criteria

Hello, I'm currently working on generating JSON data and need assistance with the following code snippet: generateArray(array) { var map = {}; for(var i = 0; i < array.length; i++){ var obj = array[i]; var items = obj.items; ...

How can TypeScript be used to enable CSV or PDF export in a material-react-table?

Is it possible to incorporate the ability to export data to CSV or PDF in a material-react-table? While I am familiar with how to do this with a Material UI table, I have not been able to find the same functionality for the material-react-table. Thank you ...

What could be the reason for certain Angular modules importing successfully while others fail to do so?

I am encountering an issue with a module that I am struggling to import. Using Typescript 2.7 and Node 10 The pxl-ng-security module is showing an error in both VSCode and VS2019. When hovering over it, error 2307 is displayed. Below is the import secti ...

Is it possible for Angular2 to map a lone JSON object?

Dealing with a JSON response that is a single object, rather than an array, can be tricky. Recently in my project, I encountered a situation where I needed to map and use such a response from an API to fill out a template. It seemed like a simple task at f ...

Angular - developing a custom web element to enhance the project

Is there a way to convert a single module into a web component and integrate it within the same project? Specifically, I have 3 modules in my project and I am looking to transform only module1 into a web component and incorporate it seamlessly. Thank you! ...

Is there a way to verify if the database has been successfully saved and the API call has been

I am currently in the process of developing a function that calls two other functions. Function 1 is responsible for saving an object to a database, while function 2 performs an API call. async createMSCalendarEntry(start: Date, end: Date, name: string ...

Integration of Mocha with WebStorm

WebStorm offers a useful feature that adds a small arrow next to describe() and it() keywords when writing tests with Mocha, allowing for easy manual execution. However, there is a challenge: I require additional setup before each test, leading me to use ...

Encountering the error message "Received 1 argument, when expecting 4" while attempting to utilize a vuex getter in TypeScript

I encountered an issue while unit testing a getter function. The error message Expected 4 arguments, but got 1. appeared when I attempted to use the getter. My application was built using Quasar and utilizes TypeScript. The value of HttpMocks.mockToken is ...

Resolving NestJS Custom Startup Dependencies

In my setup, I have a factory responsible for resolving redis connections: import {RedisClient} from "redis"; export const RedisProvider = { provide: 'RedisToken', useFactory: async () => { return new Promise((resolve, reject ...

Pass an array of objects to an Angular 8 component for rendering

Recently, I started working with Angular 8 and faced an issue while trying to pass an array of objects to my component for displaying it in the UI. parent-component.ts import { Component, OnInit } from '@angular/core'; @Component({ selector: ...

A Model in TypeScript

{ "title": { "de-DE": "German", "fr-FR": "French", "en-CA": "English" }, "image": "/tile.jpg", "url": "/url/to/version" } After receiving this JSON data, my model structure is as follows: export class MyModelStruct ...

What is the best method for altering a route in React while utilizing Typescript?

I recently started coding along with the ZTM course and am working on a face recognition app. Instead of using JavaScript, I decided to use TypeScript for this project in order to avoid using the any type. However, as a beginner in this language, I'm ...

React is inferring the type of the 'charts' property in the object literal as 'any[]'

ide: vscode typescript: 2.7.1 react: 16.3.0-alpha.1 interface IState { numbers: number[]; } class CustomCanvas1 extends React.Component<undefined, IState> { constructor(properties: undefined) { super(properties); this.state = { ...

What is the most effective way to eliminate all values in an object key array except for one specific value?

Currently, I am developing an angular project and have encountered an object with the following structure: const obj = { fruits: ['apple', 'orange', 'None'], nation: ['usa'], city: ['New York', ' ...

Organizing Telephone Number Entries in Angular

In my search for a way to format a phone number input field in Angularjs, I have come across many solutions, but none specifically for Angular 7. What I am looking to achieve is for the user to enter the textfield like so: 123456789 and have the textfi ...