toasties
toasties

Reputation: 211

In Typescript how to do I make a class definition available

I'm new to typescript and I'm trying to migrate an existing project. It's written with Durandal so makes use of AMD.

My question is how to make the definitions of Classes I've written available to other files for use for things such as parameter definitions or interfaces.

To be a bit clearer. I've defined a class such as

class Example{
   constructor(){
     //some other code
   }
}
 export = Example

If I want to instantiate that class I import it with require and thats all fine.

But what if I just want to use it in another file as a parameter type e.g.

function(value:Example){
}

Or in an interface

interface exampleInterface{ 
   value:Example
}

I can import it using require in the first example, but this doesn't seem like the correct way since I'm emitting code when all I'm doing is using the class for compile time. And if I use require in the second example, the interface is no longer visible to the other classes.

The only way I've found so far is to declare an ambient version of the class in a seperate file. That works but is an obvious duplication and a problem for maintanence.

Is there a better way?

Thanks

Upvotes: 1

Views: 39

Answers (1)

basarat
basarat

Reputation: 276191

I can import it using require in the first example, but this doesn't seem like the correct way since I'm emitting code when all I'm doing is using the class for compile time

This is the recommended way. Basically it ensures that the the file that has the class definition is parsed by the runtime before this file. Note that if you don't use the imported stuff as a variable then the code emit does not take a dependency.

See Import Type Only for docs.

Upvotes: 2

Related Questions