0

Is it incorrect to use this code in a TypeScript file in Visual Studio 2013 for a Node.js code base?

// toolset_1.ts, this file is referenced in other .ts files
declare function require(name: string);
declare var module;

declare var __dirname;

Setup:

  • Project is created using node in a directory.
  • A TypeScript project created in the same directory, using VS 2013.

Current Situation/Configuration:

  • Me: C# developer, Node.js and TypeScript noob.

  • TypeScript: Module system option is set to None.

  • Project Description: A simple play ground with Node.js, Express.js and bunch of other tools with some TypeScript code.

  • Project Status: It works (Simple GET(Hogan.js), POST, PUT and DELETE request are being servered)

For example this is pile.ts in routes directory (express):

/// <reference path="./lib/toolset_1.ts" />

var express = require('express');
var router = express.Router();

router.get('/', function (req, res, next) {
    res.render('pile', { title: 'PILED', msg: '[PILED]' });
});

router.post('/', function (req, res) {
    res.send({ time: new Date(), msg: 'post [PILED]' });
});

router.put('/', function (req, res) {
    res.send({ time: new Date(), msg: 'put [PILED]' });
});

router.delete('/', function (req, res) {
    res.send({ time: new Date(), msg: 'delete [PILED]' });
});

module.exports = router; 

1 Answer 1

2

Is it incorrect to use this code in a TypeScript file in Visual Studio 2013 for a Node.js code base?

It is okay. But I would do something else:

  • get the file node.d.ts from definitely typed. Also get others like express.d.ts
  • reference the file using /// <reference
  • compile with commonjs : --module commonjs
  • Use import/require instead of var/require:

i.e.

import express = require('express');

More on external modules : https://www.youtube.com/watch?v=KDrWLMUY0R0

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

4 Comments

Thanks; the things is (IMHO; currently - TypedScript and Node.js noob) I do not like the idea of "wrapper code". If it's JavaScript, let it be. I write my portion of code in TypeScript and can use latest updates of those js libs without waiting for their ts wrappers to get updated. But i'll try them (it's wise to listen to experts!).
@KavehShahbazian bear in mind that the .d.ts file is not actually code. It just declares the "shape" of the real code. The alternative is to just treat all objects as having type any, but then you might as well be using JavaScript.
@DanielEarwicker I suppose then .d.ts files is some sort of header file. And thanks for DefinitelyTyped, it works great.
Yes the analogy with C header files is very apt.

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.