How does Typescript handle dependency injection compared to the JSDoc typedef module import for defining types?

Currently, I am facing an issue with defining dependency injection in Typescript.

In my experience with JSDoc, I have used

typedef import('./classModule.js').default myClass
.

To illustrate, let's consider multiple classes stored in their own module files - classes A and B. In this scenario, we aim to specify that class B requires an instance of class A as a dependency in its constructor.

// A.js

export default class A {
  //...
}
// B.js

// Using jsdoc, I can
/**
 * @typedef {import ('./A').default} A
 */

export default class B {
  /**
   * @param {A} a
   */
  constructor (a) {
    this.a = a
  }
}

What makes this interesting is that it's simply a comment. No actual import takes place.

But how can this be accomplished in Typescript?

From what I gather, I can utilize typeof A for use as a type. However, the challenge lies in having to import the class module for this, which is not ideal.

Instead, I would prefer to import an interface that has been generated from my class. This way, at runtime, there are no real dependencies or imports involved.

Answer №1

To implement type-only imports in TypeScript 3.8 or later, you can use the following method:

import type X from './X';

export default class Y {
    x: X;
    
    constructor(x) {
        this.x = x;
    }
}

The import type statement is specifically used for importing declarations that are only to be utilized for type annotations and declarations. It is completely removed during compilation, leaving no trace at runtime.

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

Is there a way to reset the selected value of a specific option in Mat-Select?

Using mat-select, I need to reset the selection for a specific value of mat-select's mat-option. For instance, take a look at this example on StackBlitz In the example, the mat-select has three options; when selecting Canada, it should revert back t ...

Is Angular 2 Really Suitable for Multi-Page Applications?

I am currently working on a multi-page app using Angular2 and have noticed that the load times are slower than desired when in development mode. While searching for solutions, I came across a thread on stackoverflow that explains how to set up Angular2 fo ...

Utilizing Vue class-style components for creating a recursive component

I'm currently working with a class-style component using the vue-property-decorator plugin. I want to create a recursive component that can use itself within its own structure. Here's a snippet of my code: <template> <ul> <li& ...

What could be causing the issue with the variable appearing as undefined in

My class has a property: public requestLoadPersonal: Personal[] = []; As well as a method: private filterByGender(selectedValue: any): void { console.log(this.requestLoadPersonal); this.requestLoadPersonal = this.requestLoadPersonal.filter( ...

Convert a fresh Date() to the format: E MMM dd yyyy HH:mm:ss 'GMT'z

The date and time on my website is currently being shown using "new date()". Currently, it appears as: Thu May 17 2018 18:52:26 GMT+0530 (India Standard Time) I would like it to be displayed as: Thu May 17 2018 18:43:42 GMTIST ...

Guide on invoking personalized server-side functions (such as object parsing) utilizing Typescript and Angular tools

I've been grappling for weeks to make custom service calls function with Typescript / Angular / C#. It's been a challenge to find a workable solution online, and the more I search, the more bewildered I become. My current approach has largely be ...

`Unable to update the checked prop in MUI switch component`

The value of RankPermission in the switchPermission function toggles from false to true, but for some reason, the MUI Switch component does not update in the browser. I haven't attempted any solutions yet and am unsure why it's not updating. I&ap ...

How to empty an array once all its elements have been displayed

My query pertains specifically to Angular/Typescript. I have an array containing elements that I am displaying on an HTML page, but the code is not finalized yet. Here is an excerpt: Typescript import { Component, Input, NgZone, OnInit } from '@angul ...

Adjust dropdown options based on cursor placement within textarea

I have a textarea and a dropdown. Whenever a user selects an option from the dropdown menu, it should be inserted into the text area. However, I am facing a bug where the selected value is being inserted at the end of the text instead of at the current cur ...

Schedule - the information list is not visible on the calendar

I am trying to create a timeline that loads all data and events from a datasource. I have been using a dev extreme component for this purpose, but unfortunately, the events are not displaying on the calendar. Can anyone offer any insights into what I might ...

Invalid NPM package detected while deploying: @types

As I try to set up my first application with Azure's continuous development, I am facing some issues. The app is a standard template from Visual Studio 2017 MVC net core 2.0, using React. After pushing the app to my GitHub repository and configuring a ...

The process of implementing ngOninit with asynchronous data involves handling data that may take

Within the ngOnInit method, I am calling a service method and assigning the return value to a member variable. However, when trying to access this variable later in the ngOnInit again, it seems that due to synchronization issues, the value has not been ass ...

Distribute a TypeScript Project on NPM without exposing the source code

Issue: My library consists of numerous .ts files organized in structured folders. As I prepare to publish this library, I wish to withhold the source (typescript) files. Process: Executing the tsc command results in the creation of a corresponding .js fil ...

Tips for defining the types of nested arrays in useState

Looking for guidance on how to define types for nested arrays in a useState array This is my defined interface: interface ToyProps { car: string | null; doll: number | null; } interface SettingsProps { [key: string]: ToyProps[]; } Here is the stat ...

What is preventing me from utilizing a union type in conjunction with redux connect?

Below is a brief example of the code I am working on: import { connect } from "react-redux"; interface ErrorProps { error: true; description: string; } interface NoErrorProps { error: false; } type TestProps = ErrorProps | NoErrorProps; ...

Implementing various custom validation techniques in Angular 2

I am encountering an issue with adding multiple custom validations to a form. Currently, I am only able to add a single custom validation to my form. How can I include multiple validations? For example: this.user = this.fb.group({ name: ['', ...

How can I position ports on the right side of a graph element in JointJS?

I'm in the process of developing an Angular application that allows users to dynamically create graphs. Currently, I am working on a function that adds ports to vertices and I want the user to be able to select the position of the port (right, left, t ...

Is it possible to define TypeScript interfaces in a separate file and utilize them without the need for importing?

Currently, I find myself either declaring interfaces directly where I use them or importing them like import {ISomeInterface} from './somePlace'. Is there a way to centralize interface declarations in files like something.interface.ts and use the ...

Encountering unexpected errors with Typescript while trying to implement a simple @click event in Nuxt 3 projects

Encountering an error when utilizing @click in Nuxt3 with Typescript Issue: Type '($event: any) => void' is not compatible with type 'MouseEvent'.ts(2322) __VLS_types.ts(107, 56): The expected type is specified in the property ' ...

Creating a seamless integration between Angular 2's auth guard and observables to enhance application security

I'm having trouble setting up an auth guard for one of my routes because I am unsure how to implement it with an observable. I am using ngrx/store to store my token. In the guard, I retrieve it using this.store.select('auth'), which returns ...