dab dab - 5 months ago 101
Javascript Question

Typescript cannot find name of own class when importing Node.js

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?

Answer

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

Comments