What are the steps to enable full functionality of the strict option in TypeScript?

Despite enforcing strict options, TypeScript is not flagging the absence of defined types for port, req, and res in this code snippet. I am using Vscode and wondering how to fully enforce type checking.

import express from 'express';

const app = express();
const port = 3000;
app.get('/', (req, res) => {
  res.send('Hello !');
});
app.listen(port, err => {
  if (err) {
    return console.error(err);
  }
  return console.log(`server is listening on ${port}`);
});

tsconfig.json

{
  "compileOnSave": true,
  "compilerOptions": {
    "module": "commonjs",
    "esModuleInterop": true,
    "target": "es6",
    "moduleResolution": "node",
    "sourceMap": true,
    "outDir": "dist"
  },
  "strict": true,    
  "lib": ["es2015"],
  "--isolatedModules":true,
}

Answer №1

The compiler option --strict in TypeScript is a convenient shorthand for multiple individual compiler options that do not require you to annotate variables or parameters extensively. The type inference capability of the compiler allows it to determine types for unannotated variables and parameters, following the preferred convention in most cases. Only when the compiler cannot infer a suitable type and defaults to using any will --strict flag an error about missing annotations. This is primarily to discourage the use of the potentially unsafe any type with --noImplicitAny.

In the code snippet above, the unannotated constants like app, port, req, and res are inferred by the compiler to be of specific types without explicit annotations, as if they had been annotated manually.

The only instance where the compiler encounters an issue is within the parameter declaration of the err variable in the callback function for app.listen(). Here, since there is no context for determining the type, the compiler resorts to assigning any as the type for err, prompting the need for manual annotation:

app.listen(port, (err: any) => {
  if (err) {
    return console.error(err);
  }
  return console.log(`server is listening on ${port}`);
});

If you desire notifications for every unannotated variable or parameter, consider using linting tools like TSLint or ESLint alongside TypeScript.

TSLint offers rules like typedef, which mandates the presence of type definitions. Sub-options cater specifically to function parameters and variable declarations.

ESLint provides a similar rule called typedef that enforces the existence of type annotations, with sub-options available for fine-tuning its behavior.

While these tools can assist in achieving the desired behavior, keep in mind that embracing type inference is generally recommended. As stated in ESLint's documentation for typedef: "if you do not find writing unnecessary type annotations reasonable, then avoid enforcing this rule."


I hope this information proves helpful; best of luck!

Link to Playground Code

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

Node.js Express: Bizarre Symbols when downloading XLSX File Attachment

Utilizing the xlsx-populate module in conjunction with node.js, I am transmitting the workbook as a buffer according to their guidelines. When using Postman to access the API and retrieve the xlsx file as an attachment, the response contains strange charac ...

What steps can I take to improve this code and prevent the error "Property 'patient' does not exist on type 'Request<ParamsDictionary>'" from occurring?

I'm having some issues with my code. I am attempting to use passport authenticate in order to save patient information that is specific to the token generated for each individual. router.get("/current", passport.authenticate("jwt", { session: false }) ...

Leverage the power of ssh2-promise in NodeJS to run Linux commands on a remote server

When attempting to run the command yum install <package_name> on a remote Linux server using the ssh2-promise package, I encountered an issue where I couldn't retrieve the response from the command for further processing and validation. I' ...

Limit the frequency of function calls in Typescript

Update: After some research, I've learned that throttle has the capability to drop excess function invocations, making it unsuitable for my needs. I am still seeking an idiomatic solution to process every item in a queue at an appropriate pace without ...

Creating a blank zip file using the archiver module in node.js

I am currently attempting to archive a folder by utilizing archiver. The structure of the folder that I wish to archive is as follows : Project | app.js | tmp | folderToArchive │file1.txt │file2.txt │fil ...

Having trouble accessing Express from the Windows 7 console with the latest version of Express

I'm a beginner in node js and I'm attempting to install express globally. npm i -g express Everything completes successfully, but when I try to run express --help it gives me an error saying it's not recognized as an internal or external ...

Obtaining the nextauth JWT token for the backend

I have a specialized nextjs application that utilizes nextauth for user authentication, while the backend is powered by express.js. My current challenge involves sending a jwt token from nextauth to the backend when making API calls from the frontend. Thi ...

Save the socket.id from Socket IO into the Express session

Currently, I am working on a web application that utilizes Angular and Express. To handle database updates, I have implemented a REST API and incorporated SocketIO for real-time client updates. I have managed to track a list of active socket IDs for each ...

What is the best way to generate a type that generates a dot notation of nested class properties as string literals?

In relation to the AWS SDK, there are various clients with namespaces and properties within each one. The library exports AWS, containing clients like DynamoDB and ACM. The DynamoDB client has a property named DocumentClient, while ACM has a property call ...

Encountering Typescript errors when trying to destructure a forEach loop from the output of

There are different types categorized based on mimetypes that I am currently working with. export type MimeType = 'image' | 'application' | 'text'; export type ApplicationMimeType = '.pdf' | '.zip'; expor ...

Webpack resolve.alias is not properly identified by Typescript

In the Webpack configuration, I have set up the following: usersAlias: path.resolve(__dirname, '../src/pages/users'), In my tsconfig.json, you can find: "baseUrl": ".", "paths": { "usersAlias/*": ["src/pages/users/*"], } This is how the cod ...

Having trouble retrieving a value from the img.onload event handler. A 'boolean' type error is being thrown, indicating it cannot be assigned to type '(this: GlobalEventHandlers, ev: Event) => any'

In my Angular application, I have implemented a method that verifies the size and dimensions of an image file and returns either false or true based on the validation result. Below is the code snippet for this function: checkFileValidity(file: any, multipl ...

What causes the error message saying 'undefined' cannot be assigned to the specified type ...?

I just finished developing an innovative Angular application. Within the app.component.html file, I have included: <bryntum-scheduler #scheduler [resources] = "resources" [events] = "events" [columns] = "schedul ...

Experiencing an issue when attempting to deploy Strapi CMS with TypeScript on Railway - encountering the error message: "Unable to locate module 'typescript'"

Issue with Deploying Strapi CMS in TypeScript to Railway Currently facing challenges while trying to deploy Strapi CMS written in TypeScript to Railway. Despite the availability of a JavaScript template, there's a lack of a specific TypeScript templa ...

Running code in NodeJS with Express when a page is loaded

My goal was to verify the URL against an array and redirect it to an error page if necessary. I'm uncertain about how to execute code upon page load. I've searched extensively for a solution, but haven't found one yet. ...

Having difficulty storing duplicate requests that are crucial for various services/components

Currently, I am tackling a project that involves displaying multiple sets of data to the user. Each set requires several requests to be made to the backend. Specifically, for the UserDetails dataset, I must query the getUser and getSigns endpoints. However ...

TypeError: Unable to find TextEncoder in mongoose and jest when using TypeScript

Currently, I am working on a project using Node 14 along with Express v4.16.3 and Typescript (v4.7.4). Recently, I added Mongoose (v6.5.2) to the project, and while the logic code seems fine, most of the tests executed by Jest (v26.4.2) are failing with th ...

When we mention TypeScript and CDK, we are actually talking about the very foundation

As I was working on my current Stack constructor, I came across the Stack.formatArn() method. I started to wonder about the difference between using this.formatArn() and cdk.Stack.of(this).formatArn(). After all, shouldn't "this" refer to the stack it ...

Is NoSQL supported by the MySQL Community Edition?

I have decided to dive into learning and developing a Node.js application with SQL. I am aware that the MySQL Enterprise Edition offers support for NoSQL, but I'm curious if the community edition also supports NoSQL or if I need to invest in the enter ...

What is the best method for extracting individual JSON objects from a response object and presenting them in a table using Angular?

After receiving a JSON Array as a response Object from my Java application, I aim to extract each object and display it on the corresponding HTML page using TypeScript in Angular. list-user.component.ts import { HttpClient } from '@angular/common/h ...