Declaring a function type with a void parameter type in typescript

Embarking on my journey with ts and currently exploring TypeGraphQL. I came across something that caught my attention and seems unfamiliar to me:

export declare type ReturnTypeFunc = (returns?: void) => ReturnTypeFuncValue;

How should this type be understood? What is the significance of (returns?: void) in this context?

Answer №1

The ReturnTypeFunc type is utilized within the Query decorator:

export declare function Query(returnTypeFunc: ReturnTypeFunc, options?: AdvancedOptions): MethodDecorator;

This is a common usage of the Query decorator:

  @Query(returns => [SampleObject])

To enhance readability, the returns parameter was added: This query returns an array of SampleObject. Without the returns argument in the ReturnTypeFunc type, you would need to write @Query(() => [SampleObject]) instead.

Other decorators that feature an optional void argument include:

@Resolver(of => Recipe) // This resolver is for Recipe. Refer to the ClassTypeResolver.

@Field(type => [Rate]) // This field is of type Rate. Refer to the ClassTypeResolver.

Note:

  1. It should be noted that only null (if strictNullChecks is not specified) or undefined can be assigned to a variable of type void.
  2. The decorators mentioned are used to annotate classes and generate the GraphQL schema by utilizing the provided metadata. It is important to understand that defining a function with a type of ReturnTypeFunc is not recommended. The purpose of using parameters of type void is primarily for code readability.

Answer №2

The function signature provided can be found here, and it utilizes an optional parameter of type void for various reasons.

One possible reason could be to restrict callers from providing an argument in normal scenarios, while allowing internal library code to access undocumented, internal logic that may rely on the functionality of the value.

Here is a somewhat contrived example to illustrate this concept:

TS Playground

function fn (param?: void): void {
  if ((param as any) === 'log a special message') {
    console.log('Internal behavior matched');
  }
};

fn(); // Ok
fn('hello'); // Not ok

/**
 * Written as returning void, but actually returns
 * something that is used for internal library behavior
 */
function internalFnForInteralThings (): void {
  return 'log a special message' as any;
};

fn(internalFnForInteralThings()); // Ok (and logs "Internal behavior matched")

To truly understand the reasoning behind such a signature, one would need to thoroughly analyze the entire codebase of the project exporting the type and assess how it is utilized in each scenario. With this knowledge, one can potentially deduce the rationale behind the author's decision to structure the signature in this manner.

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

How to Guarantee NSwag & Extension Code is Positioned at the Beginning of the File

In my project, I am using an ASP.Net Core 3.1 backend and a Typescript 3.8 front end. I have been trying to configure NSwag to include authorization headers by following the guidelines provided in this documentation: https://github.com/RicoSuter/NSwag/wik ...

Angular Error TS2554: Received x arguments instead of the expected 0 on piped operators

I encountered an issue with Error TS2554: Expected 0 arguments, but got 4 when dealing with the observable getHappyDays(). The getHappyDays() Observable returns either Observable<HttpResponse<IHappyDays>> or Observable<HttpErrorResponse> ...

What are the tips for using ts-node in the presence of errors?

While developing, I have encountered some issues with ts-node. When I need to test something, commenting out code is my usual approach. However, when using ts-node, I keep getting this error message: 'foo' is declared but its value is never rea ...

What is the best way to implement promise function in a JavaScript functional method such as forEach or reduce?

I have implemented a promise function in the following way: // WORK let res = {approveList: [], rejectList: [], errorId: rv.errorId, errorDesc: rv.errorDesc}; for (let i = 0; i < rv.copyDetailList.length; i ++) { const item = rv.copyDetailList[i]; ...

Setting null for HttpParams during the call

I am encountering an issue with HttpParams and HttpHeaders after upgrading my project from Angular 7 to Angular 8. The problem arises when I make a call to the API, as the parameters are not being added. Any assistance in resolving this matter would be gre ...

Combining existing CSS classes with node labels in Cytoscape JS for Angular: A Guide

My project follows a consistent CSS theme, but the node's CSS style doesn't match. I'm looking to adjust the label colors in the CSS based on whether it's day mode or night mode. How can I accomplish this? this.cy = cytoscape({ con ...

Unable to transfer variable from a function to the test in Protractor

Currently, I am working on a test to verify the amount of gold in my possession. The test is being conducted using TypeScript and Protractor. Within this testing scenario, I have a method named GetAmountOfChips: public static GetAmountOfChips(): PromiseL ...

Tips for deleting multiple objects from an array in angular version 13

I am facing an issue where I am trying to delete multiple objects from an array by selecting the checkbox on a table row. However, I am only able to delete one item at a time. How can I resolve this problem and successfully delete multiple selected objects ...

I am encountering an issue where my application is not recognizing the angular material/dialog module. What steps can I take to resolve this issue and ensure that it functions properly?

For my Angular application, I am trying to incorporate two Material UI components - MatDialog and MatDialogConfig. However, it seems like there might be an issue with the placement of these modules as all other modules are functioning correctly except fo ...

Tips for setting a new key and value for an existing object in TypeScript

As I transition from JavaScript to TypeScript, I am currently working on creating a Discord bot using TypeScript to familiarize myself with the environment. However, I encountered an error when attempting to add new keys to an object that was previously cr ...

Validation Form Controls

Here is a piece of code that works for me: this.BridgeForm = this.formBuilder.group({ gateway: ["", [Validators.required, Validators.pattern(this.ipRegex)]], }); However, I would like to provide more detail about the properties: this.BridgeF ...

The editor is locked and choices are displayed in a vertical orientation

I'm currently experimenting with using draft js in my project to create a wysiwyg editor. However, I've encountered an issue where the editor appears vertically instead of horizontally when I load the component. Any idea why this might be happen ...

The operation of assigning the value to the property 'baseUrl' of an undefined object cannot be executed

I recently created a JavaScript client using NSWAG from an ASP .NET Rest API. However, I am encountering some errors when attempting to call an API method. The specific error message I am receiving is: TypeError: Cannot set property 'baseUrl' of ...

Ways to access a property within an object using TypeScript

Can you help me extract the "attributes" array from this object and store it in a new variable? obj = { "_id": "5bf7e1be80c05307d06423c2", "agentId": "awais", "attributes": [ // that array. { "created ...

Deliver the commitment to the data source connection settings in TypeORM

Is it possible to retrieve the datasource connection options from AWS Parameter Store instead of storing them as environment variables in a general JavaScript question? I am having difficulty finding a solution and seeking expert advice on this matter. Th ...

Using a dictionary of class types as input and returning a dictionary of their corresponding instances

Is there a way to create a function that takes a dictionary with class values as an argument and returns a dictionary of their instances? For example: classes C1, C2 function f: ({ name1: C1, name2: C2 }): ({ name1: new C1() name2: new C2 ...

Validate the button's status in Ionic

When I click on a button, I am trying to retrieve the Toggle state immediately. However, I consistently receive a value of true, even when my toggle is actually set to false. I believe the issue lies in how I am manipulating the DOM. Here is an example ...

The "shape" property is not available while utilizing generics with toZod

Short version: I encountered a type error, and here is the link to the TS PLAYGROUND I am looking to ensure type safety when creating zod schemas. To achieve this, I define the data type like so: type Option = { id: number }; Using this type definition ...

Nearly every category except for one from "any" (all varieties but one)

In Typescript, is it feasible to specify a type for a variable where the values can be any value except for one (or any other number of values)? For instance: let variable: NOT<any, 'number'> This variable can hold any type of value excep ...

Creating an Http interceptor in Ionic 3 and Angular 4 to display a loading indicator for every API request

One of my current challenges involves creating a custom HTTP interceptor to manage loading and other additional functions efficiently. Manually handling loading for each request has led to a considerable increase in code. The issue at hand: The loader is ...