What is the correct method for using typedef to define a function with the signature "() => void" in accordance with tslint guidelines?

Currently, I am working on a function that requires specific typing:

const checkIfTagNeedsToBeCounted = (listOfTags: string[]): boolean => {
  const tagsToExcludeFromCounting: string[] = [
    "DoNotCount",
  ];

  const excludedTagFound: boolean = listOfTags.some(
    (singleTag) => tagsToExcludeFromCounting.includes(singleTag),
  );

  return !excludedTagFound;
};

However, when I try to define it with

const checkIfTagNeedsToBeCounted: Function = ...

I receive a warning from tslint:

Avoid using 'Function' as a type. It is recommended to use a specific function type, such as () => void. (ban-types)

While I have been temporarily silencing this issue with

// tslint:disable-next-line: ban-types
const checkIfTagNeedsToBeCounted: Function = (listOfTags: string[]): boolean => {

I am curious to learn the correct way of typing a function according to tslint?

Answer №1

Function is not specific enough on its own.

TypeScript advises that you must precisely define the function's prototype for better results.

This will enable auto-completion and error detection for issues such as incorrect parameters, etc.

You have two options to address this: either let TypeScript infer the function type automatically,

or manually specify the type of the function yourself.

REMINDER: Opt for the second choice if TypeScript struggles to infer correctly (usually when using any extensively) or if you want to reuse the type definition.


In your scenario:

const checkIfTagNeedsToBeCounted: (listOfTags: string[]) => boolean = (listOfTags: string[]): boolean => {
   // ...
};

If you wish to reuse the function type :

type MyFunction = (listOfTags: string[]) => boolean;

const checkIfTagNeedsToBeCounted: MyFunction = (listOfTags: string[]): boolean => {
   // ...
};

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

Obtain the object literal string with additional decorative strings surrounding it

In my current Typescript code, I have an object literal structured like this: const MyNamesStrings = { a: { b: "hello", c: "bye" } d: { e: "qwerty" } } However, I am looking for a way to wrap these strings with add ...

Angular 5+ does not have any compatible call signatures for Type Search

Utilizing an addItem function that I found on this site, I encountered the following error message: Error TS2349 (TS) Cannot invoke an expression whose type lacks a call signature. Type 'Search' has no compatible call signatures. Definition o ...

The error "TypeError: Cannot read property 'match' of undefined" occurs when trying to access the match property on an undefined value

Just a few minutes back, I set up a new project in the latest version of Ionic. I included import { HTTP } from '@ionic-native/http' and then proceeded to send a GET request to my backend application. meetingsUrl: 'http://localhost:8080/ ...

Having trouble triggering the button with querySelector in Angular

I have a dynamic page where I need to click on a button. I tried the code below, but it is not working and not showing any alert. However, if we use the same code in the browser console, it executes and shows an alert. Can someone please suggest how to r ...

Unable to import Express in Angular

In my Angular app, there are no syntax errors present. Within a file titled test1.js, I have only one line of code: var express = require('express'); However, I am encountering an error in my log: (Interestingly, commenting out this single l ...

How to pass down TypeScript interface props to component in Next.js?

When using an interface with defined props for API data, everything works fine if the data is used directly on the page where the interface is defined. However, when passing the data down to a component, an error message of Binding element 'site' ...

Retrieving parameter types of class methods from generic types with indexing

Within my class, I have various functions along with a non-function property: class Example { methodA(param1: string, param2: number) {} methodB(): string {} methodC(param1: boolean, param2: number): number {} prop1: string = ''; ...

Having trouble with VueJS ref not preventing the default form action on submit?

Within my <script> tag, I currently have the following code: render(createElement) { return createElement("form", {ref: "formEl" , on: {submit: this.handleSubmit} }, [ <insert create form inputs here> ]); } handleSubmit(e) { ...

I am currently making use of the Material UI accordion component and I would prefer for it to not collapse unless I specifically click on the expandIcon

I have been utilizing the Material UI accordion component and am currently struggling to find a solution that prevents the panel from collapsing when it is clicked. Ideally, I would like to manage the opening and closing of the panel solely through click ...

Having difficulties testing the Angular HTTP interceptor with Karma and Jasmine

Testing an http interceptor has been quite the challenge for me. Despite having my token logged in the console and ensuring that the request URL matches, I still can't figure out why it's not working with the interceptor in place. Interestingly, ...

Troubleshooting: Difficulty assigning a value to a nested object in Angular

I'm a beginner in Angular and TypeScript so please forgive me if this question seems silly. I am attempting to store the value of a returned object into a nested property within an object with a type of any. Unfortunately, it is not allowing me to do ...

Combining different types in object keys helps prevent errors when working with TypeScript

Let's create a function type VarietyType = 'choice1' | 'choice2' const myFunction = (arg: Partial<Record<VarietyType, number>>) => { console.log(arg) } When calling it with an argument of the incorrect type myFunc ...

Is there a way to use Regex to strip the Authorization header from the logging output

After a recent discovery, I have come to realize that we are inadvertently logging the Authorization headers in our production log drain. Here is an example of what the output looks like: {"response":{"status":"rejected",&quo ...

Tips for managing local storage asynchronously

I have two files in my TypeScript application, namely: File 1 and File 2, In File 1, I want to save a value in local storage like this: private load() { return this.entityService .load(this.$scope.projectRevisionUid) ...

What is the best way to verify a numerical input in a React component?

When I use the return statement, I attempt to validate a number and if it's not valid, assign a value of 0. However, this approach doesn't seem to be working for me. Is there an alternative method to achieve this? return ( <Input col ...

Zod data structure featuring optional fields

Is there a more efficient way to define a Zod schema with nullable properties without repeating the nullable() method for each property? Currently, I have defined it as shown below: const MyObjectSchema = z .object({ p1: z.string().nullable(), p2 ...

Tips for altering Koa's HTTP status code for undeclared paths

If an undefined route is accessed on a Koa server, what is the best method to change the default HTTP status code and response body? Currently, Koa returns a 404 status and 'Not Found' text in the body. I intend to modify this to 501 (Not implem ...

What is the best way to create a general getter function in Typescript that supports multiple variations?

My goal is to create a method that acts as a getter, with the option of taking a parameter. This getter should allow access to an object of type T, and return either the entire object or a specific property of that object. The issue I am facing is definin ...

Can you provide guidance on how to pass props to a component through a prop in React when using TypeScript?

Hey there, I'm facing an issue with TypeScript where the JavaScript version of my code is functioning properly, but I'm having trouble getting the types to compile correctly. In an attempt to simplify things for this question, I've removed ...

Why isn't the parent (click) event triggered by the child element in Angular 4?

One of my challenges involves implementing a dropdown function that should be activated with a click on this specific div <div (click)="toggleDropdown($event)" data-id="userDropdown"> Username <i class="mdi mdi-chevron-down"></i> </d ...