Aymeric Gaurat-Apelli
Aymeric Gaurat-Apelli

Reputation: 1864

Typescript + requirejs: How to handle circular dependencies?

I am in the process of porting my JS+requirejs code to typescript+requirejs. One scenario I haven't found how to handle is circular dependencies.

Require.js returns undefined on modules that are also dependent on the current and to solve this problem you can do:

MyClass.js

define(["Modules/dataModel"], function(dataModel){
  return function(){
    dataModel = require("Modules/dataModel");
    ...
  }
});

Now in typescript, I have:

MyClass.ts

import dataModel = require("Modules/dataModel");

class MyClass {

  dataModel: any;

  constructor(){

    this.dataModel = require("Modules/dataModel"); // <- this kind of works but I lose typechecking
    ...
  }
}

How to call require a second time and yet keep the type checking benefits of typescript? dataModel is a module { ... }

Upvotes: 0

Views: 454

Answers (1)

basarat
basarat

Reputation: 276181

Specify the type using what you get from import i.e

import dataModelType = require("Modules/dataModel");

class MyClass {

  dataModel: typeof dataModelType;

Upvotes: 2

Related Questions