4

I'm attempting to use a node.js class (net in this instance) in a class I have defined.

Connection.ts:

import net = require('net');
class Connection  {

}

Then I reference my class in another file,

ConnectionContext.ts:

interface IConnectionContext {
    connection: Connection;
}

When I have this code, I see an underlined "Connection" in ConnectionContext that says "IConnectionContext.ts(3,17): error TS2304: Cannot find name 'Connection'"

if I remove the import * as net from part, the compile error goes away.

I'm a bit confused, when I look at the resulting JavaScript, all my classes look identical in their creation. I'm not certain why typescript is saying the class doesn't exist.

Here's my tsconfig:

{
    "compileOnSave": true,
    "compilerOptions": {
        "module": "commonjs",
        "outDir": "bin/",
        "noImplicitAny": true,
        "removeComments": true,
        "preserveConstEnums": true,
        "sourceMap": true,
        "moduleResolution": "node",
        "target": "es5"
    },
    "exclude": [
        "node_modules"
    ]
}

Based on this, what do I need to do to get my interface to see my class that uses node.js modules?

1
  • Not very familiar with typescript, but if it's using the es2015 module spec then it appears you're mixing the node-style modules with the new module syntax: import net = require('net');. Have you tried import net from 'net';? Commented Jun 9, 2016 at 4:36

1 Answer 1

5

if I remove the import * as net from part, the compile error goes away.

In the absense of an import or export statement the file is considered global. As soon as you import / export it becomes a module and hence must be imported.

This is covered here : https://basarat.gitbooks.io/typescript/content/docs/project/modules.html 🌹

Sign up to request clarification or add additional context in comments.

3 Comments

That's a bit annoying, having to import every external class I use.. I mean, not much different than how I did it with node.js originally, which makes sense. Still a bit annoying lol.
If you have a path typo you now get a compiler error. In js + node you probably ended up with a runtime error
Right, in order to get it to work in its current form, I have to do import {Connection} from './Connection.ts'; which is kind of annoying but it makes sense from a pure node.js aspect.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.