Kev
Kev

Reputation: 5442

What is the equivalent of JSDoc typedef module import in Typescript for dependency injection?

What I am trying to resolve is a problem of declaring dependency injection in Typescript.

I am familiar with JSDoc, where I can use typedef import('./classModule.js').default myClass.

Simple example: imagine we have multiple classes in their own module files. Classes A and B. We want to declare that class B needs an instance of class A as a dependency in its constructor.

// A.js

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

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

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

What's cool here, it's that it's just a comment. No actual import is ocurring.

How do I do this in Typescript?

As far as I know I can use typeof A to use as a type. The problem is I need to actually import the class module for that, but that's not what I want to do.

I'd rather import some interface that has been derived from my class. Thus at runtime, there isn't any real dependency or import.

Upvotes: 1

Views: 843

Answers (1)

Aleksey L.
Aleksey L.

Reputation: 37918

You can use type-only import (introduced in TS 3.8):

import type A from './A';

export default class B {
    a: A;
    
    constructor (a) {
        this.a = a
    }
}

import type only imports declarations to be used for type annotations and declarations. It always gets fully erased, so there’s no remnant of it at runtime

Upvotes: 2

Related Questions