A foundational NodeJS program in TypeScript featuring a structured client-utility-definition setup with adherence to stringent coding guidelines

What is the best way to set up a basic TypeScript framework for starting a program with strict settings, based on the following program structure?

  1. An initial "client" code containing the actual program logic
  2. A separate "utility" module for defining functions and extensions (which can be used to create additional modules)
  3. A definition file that allows for extensions from the utility module mentioned in point 2.

This setup should adhere to strict TypeScript rules to fully utilize TypeScript features instead of relying solely on plain JavaScript. This involves using a tsconfig.json configuration similar to the one below:

{
  "compilerOptions": {
    "strictNullChecks": true,
    "allowJs": false,
    "alwaysStrict": true,
    "noImplicitAny": true,
    "types": [
      "node"
    ]
  }
}

To summarize, the project will enforce strict null checks, disallow plain js files, maintain consistent strict mode, eliminate implicit any types, and explicitly define each imported type within the project.

The only flexibility allowed is in the "relaxed" sections related to include, exclude, and files in the TypeScript project file. These sections ensure that only relevant .ts, .d.ts, and .tsx files located in the current directory are included in the build process, avoiding any unnecessary or unrelated source code cluttering the folder.

Answer №1

It took some effort, but I finally managed to create this structure. Sharing it for those who are new to TypeScript and looking for something similar.

Since this is a NodeJS application, the bare minimum requirements include having the @types/Node package installed using npm -i @types/Node

NPM Tasks to Complete

  1. Create package.json by running npm init
  2. Install @types/node with npm install @types/node

TypeScript Tasks to Complete

  1. Create an identical tsconfig.json file as the one provided in the question:

tsconfig.json

{
  "compilerOptions": {
    "strictNullChecks": true,
    "allowJs": false,
    "alwaysStrict": true,
    "noImplicitAny": true,
    "types": [
      "node"
    ]
  }
}
  1. Create a sample .d.ts file (extending a string with a 'test' function)

string.d.ts

interface String {
  test(this: string) : string;
}
  1. Create the utility module

utils.ts

String.prototype.test = function (this : string) : string {
  var str = this;
  str = str + " - test";
  return str;
}

function textIsTest(what : string) : boolean {
  return what == "test";
}

export { textIsTest };
  1. Your main code goes here:

index.ts

import * as util from "./utils";

let params = process.argv.slice(2); // split commandline arguments

let testString = params[0];

console.log("Commandline parameter: " + testString);
console.log("Extended string: " + testString.test());
console.log("Is 'test': " + util.textIsTest(testString));

I hope this guide will be helpful for others starting out with TypeScript!

Extra: watch + runner

A batch (bash) script to watch and run the project. It should work on cygwin, linux, and mac (tested on cygwin only):

#!/bin/bash

# Functions for spinner

... (rest of the content remains the same) ...

This script will monitor changes in files within the current directory based on their last changed time stamp. It includes a nice spinning animation while checking for changes, gracefully interrupts if ctrl+c is pressed, and will stop if the script itself is modified. Adjustments may be needed to monitor changes in subdirectories.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

I want my Angular 2 application to redirect to the appropriate page when a user who is logged out attempts to access a page that requires them to be logged in

When a user is logged out in Angular 2 router and they try to navigate to a page that requires them to be logged in, I need the app.ts file to redirect them. I am utilizing typescript along with angular 2. Oddly enough, the redirection works for certain ...

Run a script in a newly opened tab using the chrome.tabs.create() method

Struggling with executing a script using chrome.tabs.executeScript() in the tab created with chrome.tabs.create()? Despite searching for solutions, nothing seems to be working as expected. Check out my current code below: runContentScript(){ c ...

Utilizing ReactJS and TypeScript to retrieve a random value from an array

I have created a project similar to a "ToDo" list, but instead of tasks, it's a list of names. I can input a name and add it to the array, as well as delete each item. Now, I want to implement a button that randomly selects one of the names in the ar ...

The JSONP request failed with an error stating: ReferenceError: document is not defined

My internship project involves developing a mobile application based on the website www.claroline.net using Nativescript and Angular 2. I have successfully implemented the login function, allowing users to sign in to the app. Next, I need to integrate not ...

What is the reason behind TypeScript enclosing a class within an IIFE (Immediately Invoked Function

Behold the mighty TypeScript class: class Saluter { public static what(): string { return "Greater"; } public target: string; constructor(target: string) { this.target = target; } public salute(): string { ...

Angular - Implementing filter functionality for an array of objects based on multiple dropdown selections

I am currently working on filtering an array of objects based on four fields from a form. These four fields can be combined for more specific filtering. The four fields consist of two dropdowns with multiple selection options and two text boxes. Upon cli ...

Create allowances for specific areas

One of my methods involves the saving of an author using the .findOneAndUpdate function. The structure of AuthorInterface is as follows: export interface AuthorInterface { name: string, bio: string, githubLink: string, ...

Find the variance between today's date and a selected date, then initiate the timer based on this variance

I have a grid containing data. I utilize the loadGrid() function to preload data or conditions before the grid finishes loading. When the active state is set to 1, my intention is to initiate a timer by calculating the difference between the current date ...

Top technique for verifying the presence of duplicates within an array of objects

How can I efficiently check for duplicates in typescript within a large array of objects and return true or false based on the results? let testArray: { id: number, name: string }[] = [ { "id": 0, "name": "name1" }, ...

...additional properties in React function components using TypeScript

Here is a snippet of code that I am working with: <InputComponent id="email" name={formik.values.email} type="text" formik={formik} className="signInInput" disabled/> However, there seems to be an issue with the disable ...

What is the best way to send props to a styled component without needing to convert them to transient props beforehand

Recently, I designed a custom Text component that accepts several props. These props are then forwarded to the styled component where specific styles are applied. However, I am facing an issue where I do not want these props to be passed down to the DOM, b ...

Display the number of objects in an array using Angular and render it on HTML

I am having trouble displaying the length of an array on my HTML page. No errors are showing up in the console either. Can someone help me figure out how to get the total number of heroes? HTML: <div *ngFor="let hero of heros"> <div>The tota ...

Setting up a variable with no operation assigned to it

As I delved into the Angular utils source code, I stumbled upon this interesting line: export const NOOP: any = () => {}; It seems pretty straightforward - a variable that doesn't perform any operation. But then, within the same library, there is ...

How can I retrieve a certain type of object property in TypeScript?

Imagine having a collection of flags stored in an object like the example below: type Flags = { flag1: string, flag2: string, flag3: boolean, flag4: number } // const myFlags: Flags = { // flag1: 'value 1', // flag2: 'value 1&ap ...

The Keyup Filter in the FromEvent function is malfunctioning and not behaving as anticipated

I have created a simple search function for my app using the FromEvent KeyUp and debounceTime features as shown in the code below: <input matInput #inputSearch> @ViewChild('inputSearch', { static: false }) input: ElementRef; fromEvent(th ...

What is the procedure for setting up the typings folder in AngularJS 1.5 with TypeScript?

I'm currently working on a project using AngularJS 1.5 and TypeScript. I need to install the "angularjs/angular.d.ts" and "angularjs/angular-route.d.ts" files. Despite installing tsd globally, when I run the command "tsd install angular," I receive a ...

Data object constructor is not triggered during JSON parsing

Currently, I am retrieving data from a server and then parsing it into TypeScript classes. To incorporate inheritance in my classes, each class must be capable of reporting its type. Let me explain the process: Starting with the base class import { PageE ...

What is the reason behind having to refresh the page or switch to another tab for the field to display?

Currently, I am in the final stages of completing my update form. However, I am facing an issue with the conditional field. The select field should display a conditional field based on the selected value. The problem I'm encountering is that I need to ...

Even after ensuring the proper type checking, I am still receiving the error message "Property 'message' does not exist on type 'object'"

I have the following code snippet: try { // api call } catch (error) { if (typeof error === 'object' && error !== null && 'message' in error) { if (typeof error.message === 'string') { if (error.me ...

Is there a way to eliminate the line that appears during TypeScript compilation of a RequireJS module which reads: Object.defineProperty(exports, "__esModule", { value: true });?

Here is the structure of my tsconfig.json file: { "compileOnSave": true, "compilerOptions": { "module": "amd", "noImplicitAny": false, "removeComments": false, "preserveConstEnums": true, "strictNullChecks": ...