Using Typescript to prevent the usage of await with Tslint

Can Tslint be utilized to restrict the usage of Typescript's await feature? If not, are there alternative linters available for this purpose?

Answer №1

This solution involves using a custom rule that serves my specific needs effectively.

To implement this solution, begin by creating a file (for example, noAwaitRule.ts) and compile it using tsc.

import * as ts from "typescript";
import * as Lint from "tslint";

export class Rule extends Lint.Rules.AbstractRule {
    public static FAILURE_STRING = "await statement forbidden";

    public apply(sourceFile: ts.SourceFile): Lint.RuleFailure[] {
        return this.applyWithFunction(sourceFile, walk);
    }
}

function walk(ctx: Lint.WalkContext<void>) {
    return ts.forEachChild(ctx.sourceFile, function cb(node): void {
        if (node.kind === ts.SyntaxKind.AwaitExpression) {
            const { expression } = node as ts.AwaitExpression;
            const keywordStart = expression.pos - "await".length;
            ctx.addFailure(
                keywordStart,
                expression.pos,
                Rule.FAILURE_STRING,
                Lint.Replacement.deleteFromTo(keywordStart, expression.getStart(ctx.sourceFile)),
            );
        }
        return ts.forEachChild(node, cb);
    });
}

If your file resides in a sub-directory (e.g., tslint-rules), include it in the tslint.json under `rulesDirectory`:

"rulesDirectory": [
    ...,
    "tslint-rules"
  ],

Additionally, in the tslint.json file, add the new rule - following naming conventions, it would be named no-await:

"rules": {
    ...,
    "no-await": true
}

A special thanks to user Amy for guiding me in this direction.

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

Using Angular to pass an index to a pipe function

Currently, I am attempting to incorporate the *ngFor index into my pipe in the following manner: <td *ngFor="let course of courses | matchesTime:time | matchesWeekday:i ; index as i">{{course.courseName}}</td> This is how my pipe is structure ...

There is no overload match for the HttpClient.get call at this time

I'm trying to set up a file download feature using a blob, but I need to extract the filename from the server's "content-disposition" header. Here's the code I have: const header = {Authorization: 'Bearer ' + token}; const config ...

Is it possible to determine the specific type of props being passed from a parent element in TypeScript?

Currently, I am working on a mobile app using TypeScript along with React Native. In order to maintain the scroll position of the previous screen, I have created a variable and used useRef() to manage the scroll functionality. I am facing an issue regardi ...

`The process of converting Typescript to ES5 through compiling/transpiling is encountering issues`

My current project involves using Webpack and integrating angular2 into the mix. To achieve this, I made adjustments to my setup in order to compile TypeScript. Following a resource I found here, my plan was to first compile TypeScript to ES6 and then tra ...

Troubleshooting Problem with Uploading Several Photos to Firebase Storage

I need assistance with uploading multiple photos to Firebase Storage. Despite my efforts, it seems that the original upload keeps getting overwritten and the folder with the venueID property is not being created. Can someone provide some guidance on this i ...

What is the best way to fetch all Firebase database IDs using Angular?

Is there a way to fetch all data from Firebase database along with their respective IDs? Currently, I have two functions - getAll() and get(input) that retrieve specific products based on the given ID. However, my current implementation only returns obje ...

Ways to conceal a table and button in the absence of data for display

I've been working on a way to hide the table and the 'changeState' button when there's no data present. Currently, I have set it up so that a message saying 'No entries in the list!' pops up briefly before disappearing, bringi ...

Components unable to exchange data using Service

Trying to pass values from one component to another, but encountering issues with the code. The values are showing as undefined on the next page. Below is the code for my service class named UtilityService.ts: import { Injectable } from '@angular/co ...

Tips for customizing the color scheme of background, rows, row selection, and headers in Angular 4 using Bootstrap 4 data tables

I've integrated Bootstrap 4 data table in my Angular 4 project, but I'm struggling to customize row colors, row selection colors, and header colors. You can check out the example of the data table I'm using at this link: https://github.com/ ...

What is the method for extracting individual elements from an object returned by a React hook in Typescript?

I am currently working on a component that needs access to the query parameters from React Router. To achieve this, I have been using the use-react-router hook package in my project. This is what I am trying to accomplish: import React from "react; impor ...

Set the default value for a form control in a select dropdown using Angular

I've been struggling to figure out how to mark an option as selected in my select element, but I haven't had any luck. I've tried multiple solutions from the internet, but none of them seem to be working for me. Does anyone out there have ...

How to create an array of objects using an object

I have a specific object structure: { name: 'ABC', age: 12, timing: '2021-12-30T11:12:34.033Z' } My goal is to create an array of objects for each key in the above object, formatted like this: [ { fieldName: 'nam ...

What function does the ng-template serve when encapsulated within an ng-select component?

Upon observing various instances of ng-select, I've noticed that it often involves wrapping a ng-template, as exemplified below: <ng-select [items]="cities" [(ngModel)]="selectedCity" bindLabel="name" bindV ...

`Error importing react-markdown in Next.js 11.1 with TypeScript``

Having trouble with importing react-markdown in my next.js SSG project. When running npm run dev, I encounter an error that prevents me from proceeding to test in next export. I understand that react-markdown is an esm package, but I'm not sure how t ...

Issue with Cypress TypeScript: Unable to locate @angular/core module in my React application

I am currently in the process of updating my Cypress version from 9.70 to 10.7.0. Although I have fixed almost all the bugs, I have encountered a strange message stating that @angular/core or its corresponding type declarations cannot be found. My applica ...

Tips for transfering variables from an electron application to the backend of an Angular project

My goal is to develop a website and desktop application using the same code base. However, due to some minor differences between the two platforms, I need a way for my Angular app to distinguish whether it has been called from the web or from Electron. I& ...

Discovering the data types for node.js imports

When starting a node.js project with express, the code typically begins like this - import express = require('express') const app = express() If I want to pass the variable 'app' as a parameter in typescript, what would be the appropri ...

ESLint and Prettier are butting heads when trying to run their commands consecutively

My package.json file includes two commands: "format": "prettier --write \"{src,{tests,mocks}}/**/*.{js,ts,vue}\"", "lint": "eslint . -c .eslintrc.js --rulesdir eslint-internal-rules/ --ext .ts,.js,.vue ...

Prisma: choose from numerous options in a many-to-many relationship with various criteria

I have a unique scenario with two tables, User and Post, that are connected through a custom many-to-many table: model User { id Int @id @default(autoincrement()) name String enabled Bool posts users_to_posts[ ...

Implementing hover intent functionality in Angular 2+

Struggling to incorporate hover intent in Angular 2. Any advice or suggestions would be greatly appreciated. ...