When the variable type is an interface, should generics be included in the implementation of the constructor?

Here is a code snippet for you to consider:

//LINE 1
private result: Map<EventType<any>, number> = new HashMap<EventType<any>, number>();

//LINE 2
private result: Map<EventType<any>, number> = new HashMap();

When the variable type is an interface, do you need to include generics in the implementation constructor? Are there any differences in TypeScript between the two lines of code?

Answer №1

There is no discernible difference between the two lines in terms of their runtime behavior. Types are completely erased at compile time, so it should not have any impact on runtime performance.

Will the type parameters resolve to the same values? TypeScript will perform type inference based on the expected return value. For example, if it expects the constructor's result to be

Map<EventType<any>, number>
, it will deduce that the type parameters for the HashMap constructor should be EventType<any> and number.

This can be observed by hovering over the HashMap constructor:


export class Map<K, V> {
  get(k: K): V { return null!; }
}

export class HashMap<K, V> extends Map<K, V> {
  get(k: K): V { return null!; }
}

let o: Map<string, number> = new HashMap() // hover over HashMap and you will see constructor HashMap<string, number>(): HashMap<string, number>

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

The efficiency of React Context API's setters is remarkably sluggish

I have a goal to implement a functionality where the background gradient of a page changes depending on whether the child's sublinks are expanded or collapsed. To achieve this, I am using the useContext hook. However, I've noticed that although e ...

How to prevent unnecessary new instances from being created by the Inject() function in Angular

Can someone please clarify if the inject() function provides different instances of a service? I suspect this might be why my code is not functioning as expected. Let's examine the code snippet below: { path: 'recipes', comp ...

typeorm migration:generate - Oops! Could not access the file

When attempting to create a Type ORM migration file using the typeorm migration:generate InitialSetup -d ormconfig.ts command, I encountered an error: Error: Unable to open file: "C:\_work\template-db\ormconfig.ts". Cannot use impo ...

Changing the font family for a single element in Next.js

One unique aspect of my project is its global font, however there is one element that randomly pulls font families from a hosted URL. For example: https://*****.com/file/fonts/Parnian.ttf My page operates as a client-side rendered application (CSR). So, ...

Update the name of the table header dynamically based on the checkbox that is selected in Vue

I am working on a project where I have checkboxes that determine the header of my table based on selection. Starting from <th>Default</th>... If checkbox1 is checked, the header will change to "CheckBox1". If checkbox2 is checked, the header ...

The custom declaration file for the 'react-dates' module could not be located

I've been struggling to create a custom declaration file for the 'react-dates' npm package, but I'm facing issues with the compiler not recognizing my declaration file. Whenever I try to import DateRangePicker from 'react-dates&ap ...

Trouble arises when extending an MUI component due to a TypeScript error indicating a missing 'css' property

We have enhanced the SnackbarContent component by creating our own custom one called MySnackbarContent: export interface MySnackbarContentProps extends Omit<SnackbarContentProps, 'variant'> { variant?: MyCustomVariant; type?: MyCustomTy ...

Is it possible for a button to be assigned to a variable upon creation, but encounter an error when trying to

const button:Element = document.createElement("button");//This works fine const button:HTMLButtonElement = document.createElement("button");//This works too const button2:Element = document.getElementsByTagName("button");//Why does this give an error? con ...

What is the method for typing an array of objects retrieved from realmDB?

Issue: Argument type 'Results<Courses[] & Object>' cannot be assigned to the parameter type 'SetStateAction<Courses[]>'. Type 'Results<Courses[] & Object>' lacks properties such as pop, push, reverse, ...

I'm having trouble importing sqlite3 and knex-js into my Electron React application

Whenever I try to import sqlite3 to test my database connection, I encounter an error. Upon inspecting the development tools, I came across the following error message: Uncaught ReferenceError: require is not defined at Object.path (external "path ...

A guide to implementing localStorage in TypeScript

When attempting to assign the object item to Product using this code: localStorage.setItem("Product", JSON.stringify(item)) The JSON string of item is not properly assigned to Product. Is there a solution to this issue? ...

Can NODE_PATH be configured in Typescript?

Before, I worked on my React app with ES6 and used NODE_PATH='src' to import files starting from the src folder. However, since switching to Typescript, I've realized that NODE_PATH is not supported. After some investigation, I discovered th ...

It is advisable for the subscriber not to halt upon encountering an error within the

Dealing with a problematic subscriber that automatically unsubscribes itself when an error occurs: observable .subscribe( (data) => { // logic encountering an error // similar to throw new Error() } ) To avoid this, I can use t ...

disappearing of vue event on single file component HTML element

I'm currently working on an ElectronJs project with Electron Forge, using the Webpack + Typescript template project In addition to that, I've integrated Vue and vue-loader for webpack in order to utilize Single File Component (SFC) files: { ...

AngularJS - Unusual outcomes observed while utilizing $watch on a variable from an external AngularJS service

Within the constructor of my controllers, I execute the following function: constructor(private $scope, private $log : ng.ILogService, private lobbyStorage, private socketService) { this.init(); } private init(){ this.lobbyData = []; this.initial ...

Error in AWS Cloud Development Kit: Cannot access properties of undefined while trying to read 'Parameters'

I am currently utilizing aws cdk 2.132.1 to implement a basic Lambda application. Within my project, there is one stack named AllStack.ts which acts as the parent stack for all other stacks (DynamoDB, SNS, SQS, StepFunction, etc.), here is an overview: im ...

Testing React Hooks in TypeScript with Jest and @testing-library/react-hooks

I have a unique custom hook designed to manage the toggling of a product id using a boolean value and toggle function as returns. As I attempt to write a unit test for it following a non-typescripted example, I encountered type-mismatch errors that I' ...

After integrating session store into my application, nestjs-sequelize is not synchronizing with any models

I'm currently working on developing a Discord bot along with a website dashboard to complement it. Everything is running smoothly, except for the backend Nestjs API that I am in the process of creating. I decided to use Sequelize as the database for m ...

Error with Angular 2 observables in TypeScript

When a user types a search string into an input field, I want to implement a debounce feature that waits for at least 300 milliseconds before making a request to the _heroService using HTTP. Only modified search values should be sent to the service (distin ...

Failed to import due to an error from the downloaded dependency

I'm encountering an import error in the @react-three module of my downloaded package. ./node_modules/@react-three/drei/node_modules/troika-three-text/dist/troika-three-text.esm.js Attempted import error: 'webgl-sdf-generator' does not cont ...