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

Encountering SUID Sandbox Helper Issue When Running "npm start" on WSL with Electron and Typescript

Can anyone help me with this issue? I have Node v8.10.0 and I'm attempting to follow a beginner tutorial on Electron + Typescript which can be found at the following link: https://github.com/electron/electron-quick-start-typescript Here is the full e ...

Is it possible to perform remote file upload using Selenium in TypeScript?

Is there a specific way to manage remote file uploads using selenium-webdriver in typescript? Here is code that functions in javascript for this purpose: import remote from 'selenium-webdriver/remote'; // import * as remote from 'selenium- ...

How to pass a value in a POST request while uploading a file using Node.js and Express.js

Exploring node for the first time. I'm trying to pass a value in a POST request similar to uploading a file. Check out my code snippet below: var express = require('express'); var app = express(); var fs = require("fs"); var bodyParser ...

issue with making simultaneous async requests in PERN stack application

In the process of developing an inventory management application using PERN stack, I encountered a challenge with a modal where I need to make 2 GET requests. While both requests return a Status 200 response when logged in the front end, the issue arises w ...

Encountering the error "TypeError: Unable to access property 'findAll' of undefined" when using Sequlize

Currently, I am in the process of developing a CRUD Application utilizing PostgreSQL, Sequelize, and Express. I have been referring to this specific tutorial as my guide. However, it appears that there might be an issue with either my model or database con ...

The process of invoking the AsyncThunk method within the Reducer method within the same Slice

Within my slice using reduxjs/toolkit, the state contains a ServiceRequest object as well as a ServiceRequest array. My objective is to dispatch a call to a reducer upon loading a component. This reducer will check if the ServiceRequest already exists in ...

encountering an issue: "trigger new TypeError('JwtStrategy needs a secret or key');"

While attempting to run my web application, I encountered the following error: throw new TypeError('JwtStrategy requires a secret or key'); ^ TypeError: JwtStrategy requires a secret or key at new JwtStrategy (/Users/smitsanghvi/Des ...

Struggle with Loading Custom Templates in Text Editor (TinyMCE) using Angular Resolver

My goal is to incorporate dynamic templates into my tinyMCE setup before it loads, allowing users to save and use their own templates within the editor. I have attempted to achieve this by using a resolver, but encountered issues with the editor not loadin ...

Modify solely the aspects included in a JSON payload

Here's a code snippet that I am struggling with: // Modifying a card router.patch('/:id', async (req, res) => { try { const card = await Card.findByIdAndUpdate( {_id: req.params.id}, ...

In the application's JavaScript file app.js, certain model properties in MongoDB/Mongoose are not defined

I am currently developing an Authentication/Session system using Express, NodeJS, and MongoDB. The Mongoose Schema that I have defined is as follows: const mongoose = require("mongoose"); const Schema = mongoose.Schema; const userSchema = new S ...

Converting a file into a string using Angular and TypeScript (byte by byte)

I am looking to upload a file and send it as type $byte to the endpoint using the POST method My approach involves converting the file to base64, and then from there to byte. I couldn't find a direct way to convert it to byte, so my reasoning may be ...

Enhance your TypeScript arrays using custom object equality functions

I am looking to utilize array functions such as contains and unique, but I want them to compare equality using my custom equals function. For instance: let arr = [{id:1,..//some more},{id:2,..//some more},{id:3,..//some more}] I need the following code ...

An issue encountered with res.download() following res.render() in Node.js

Just started working with Node JS and ran into an issue: Error: Can't set headers after they are sent. I've checked my code, and the problem seems to be related to res.download(); Is there a way to display the view without using res.render()? ...

What are some ways to streamline inline styling without having to create numerous variables?

Currently, I am in the process of constructing a tab component and establishing inline variables for CSS styling. This particular project involves a streamlit app that allows me to modify settings on the Python side. At the moment, there are four elements ...

What is the importance of moving prop types into a type or interface in React components?

Consider the scenario where I have a functional component: const MyText = ({ value }) => ( <div className="my-fancy-text">{value}</div> ); Now, when utilizing Typescript, I face the need to introduce typing. A straightforward ...

The issue of not being able to use res.flush as a function in Express-sse is

Currently, I am exploring the use of express-sse for the purpose of automatically triggering a notification and calling an API when an order is placed. Below is the code snippet for my API: router.post("/createOrder", async (req, res) => { try { ...

Ceasing the response in case the document cannot be located

My code checks for the existence of an id in the database. If it doesn't exist, it should stop the logic immediately. However, instead of returning "The provided Project Id does not exist in our database.", it currently returns "Please send all the r ...

The MEAN app is experiencing an overflow of sessions in its collection. Would it be advisable to delete the sessions to free up

I recently discovered that the sessions collection in an old MEAN app I am working on has over 38 million records, mostly due to storing sessions of bots and crawlers. To optimize database space and create a backup, I am considering clearing out this colle ...

Combine two elements in an array

I am faced with a challenge in binding values from an Array. My goal is to display two values in a row, then the next two values in the following row, and so on. Unfortunately, I have been unable to achieve this using *ngFor. Any assistance would be greatl ...

data not corresponding to interface

I am encountering an issue that says Type '({ name: string; href: string; icon: IconDefinition; } | { name: string; href: string; icon: IconDefinition; childs: { name: string; href: string; icon: IconDefinition; }[]; })[]' is missing the followin ...