Could TypeScript Compiler Overlook Incorrect Type?

Below is a straightforward example.

This design follows an MVC architecture: consider M (and its subclasses) as a model and V (and its subclasses) as a view:

abstract class M { abstract update() : void; }
abstract class V { abstract updateView (m: M) : void; }

class M1 implements M {
    fV: V;
    fName: string;
    constructor () { this.fV = new V1(); this.fName="M1"; }
    getName() : string { return this.fName; }
    update() : void { this.fV.updateView (this); }
}

class M2 implements M {
    fV: V;
    constructor () { this.fV = new V1(); }
    update() : void { this.fV.updateView (this); }
}

// ==> V1 implementation of V is incorrect but not detected by the compiler
class V1 implements V {
    updateView (m: M1) : void { console.log (m.getName() + ": update called"); }
}

var m1 = new M1();
m1.update();

// ==> incorrect use of V1 by M2 not detected at compile time, generates an error at run time
var m2 = new M2();
m2.update();

It's important to note that the following will result in a compile-time error:

abstract class X { abstract amethod () : void; }
class V2 implements V {
    updateView (m: X) : void { console.log ("V2 update called"); }
}

Is there an issue with the initial code or is it a problem with the compiler?

Your insights are greatly appreciated.

Dom

Answer №1

My code successfully compiles with typescript version 1.8.10.

abstract class Model { abstract update(): void; }
abstract class View { abstract updateView(model: Model): void; }

abstract class Controller extends Model { abstract someMethod(): void; }
class ViewTwo implements View {
    updateView(model: Controller): void { console.log("ViewTwo update called"); }
}

The key change here is that the Controller class must extend the Model class to align with what is expected in the updateView method of the View interface.

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

Having trouble declaring custom pipes in Angular

A new pipe named 'shortend.pipe.ts' has been created within the app folder. import { PipeTransform } from "@angular/core"; export class ShortendPipe implements PipeTransform { transform(value: any, ...args: any[]) { return ...

Utilizing class attributes within multiple classes

I have created a custom class called MutationValidator as follows: const ERR_MSG = 'Error1'; @Service() export class MutationValidator { .. } This class is used in another class like so: import { MutationValidator } from './mutation ...

Tips for incorporating conditional types into function parameters based on existing input

The title might be confusing, so allow me to clarify. My Objective I am referring to the code snippet below. I aim to specify the route property based on the types property as either a string or a function that returns a string. The Code Let's b ...

Angular - Unable to access property '$invalid' because it is null

Working on my login page with angular and typescript. Clicking the submit button should trigger the login function in the controller, but if the form is invalid, it should just return. New to typescript, I keep running into an error when trying to add an ...

Leveraging GetServerSideProps for Dynamic URL Query Parameters

While working on querying the parameter in the URL within getServerSideProps, I encountered an error where ID was undefined in the DetailThemepage function. My Next.js version is V.13 and the directory structure is app/detail/[id]/page.tsx. http://loca ...

Fetching attributes of a class in TypeScript

I have successfully created a "load" function that takes JSON data and loads the attributes into properties of my class. As I am experimenting with typescript for the first time, I managed to resolve most errors but there are a few remaining challenges. l ...

The unknown number of arguments in a Typescript generic type

I'm currently working on developing a function that utilizes a generic type to take in a function, an array of arguments for the function, and then apply them accordingly. However, I am facing an issue with TypeScript not correctly interpreting the ar ...

Typescript is failing to compile classes in a reliable sequential order

In my MVC 5 project, I am using TypeScript and angular. There are three TS files: Controller1.ts, Controller2.ts, and app.ts. The issue arises when I compile the program for the first time - everything usually compiles correctly in the expected order. Howe ...

Nearly every category except for one from "any" (all varieties but one)

In Typescript, is it feasible to specify a type for a variable where the values can be any value except for one (or any other number of values)? For instance: let variable: NOT<any, 'number'> This variable can hold any type of value excep ...

Adding an eventListener to the display style of a div in React: A step-by-step guide

I'm currently working on implementing a functionality in React where a Highcharts chart automatically resizes to fit its parent element whenever the parent div is shown. Unlike other libraries, Highcharts doesn't support automatic resizing when t ...

Error message: The database query function is encountering an issue where the property 'relation.referencedTable' is undefined and cannot be accessed

Currently, I am working with two schemas named products.ts and category.ts. The relationship between these files is defined as one-to-many. In the products.ts file: import { pgTable, timestamp, uuid, varchar } from "drizzle-orm/pg-core"; import ...

Beginner in Typescript - Exploring ways to verify an interface using an index

When working with a list of operations in a database, each operation may have a unique set of variables that need to be passed. To make adding new operations easier, I decided to store the interfaces within a list structure like this: const operation = { ...

What could be causing my Vue array watcher to not trigger when I add an item to the array?

Below is a brief TypeScript module: import { ref } from 'vue' import { i18n } from '~/i18n' import { ElMessageBoxOptions } from 'element-plus' const { t } = i18n.global export const toasts = ref<ElMessageBoxOptions[]>( ...

Arrangement of items in Angular 2 array

Received a JSON response structured like this JSON response "Terms": [ { "Help": "Terms", "EventType": "Success", "Srno": 1, "Heading": "Discount Condition", "T ...

Learn how to construct a specialized folder arrangement and include TypeScript within an Express server before launching it on the Heroku platform

Creating and deploying my MEAN app on Heroku has been a breeze so far. The front end is up and running smoothly on the provided website, but I'm stuck when it comes to compiling and building the server part of my app, especially since it's in Typ ...

Personalized ngIf directive featuring an included alternate template

In Angular applications, it is a common practice to use the ngIf directive with Observables to display data and provide an else template to show a placeholder while the data is loading. <data-view *ngIf="data$ | async as data; else progress" [items]="d ...

Indicate the type of content returned by a Controller

I'm dealing with a metrics.controller.ts file that looks like this: import { Controller, Get } from '@nestjs/common'; import { ApiOperation, ApiResponse, ApiUseTags, ApiModelProperty } from '@nestjs/swagger'; import { PrometheusSe ...

Performance challenges with rendering SVG in ngFor due to the presence of a highly nested array structure - in

I'm currently developing a business application that requires me to dynamically render SVG images for displaying floor plans. The SVG elements are stored in a database and provided to the front-end in JSON format, allowing the graphics to be rendered ...

Type of Request: POST Error Code: 400 Unacceptable Request Referrer Directive: strict-origin-when-cross-origin

import { Restaurant } from "@/types" import { useAuth0 } from "@auth0/auth0-react" import { useMutation } from "@tanstack/react-query" import { toast } from "sonner" const API_BASE_URL = import.meta.env.VITE_API_BAS ...

Enhanced string key indexer type safety in TypeScript

Discover and explore this online TypeScript playground where code magic happens: export enum KeyCode { Alt = 'meta', Command = 'command', // etc. } export type KeyStroke = KeyCode | string; export interface Combination { comb ...