lukeautry / tsoa

Build OpenAPI-compliant REST APIs using TypeScript and Node
MIT License
3.45k stars 494 forks source link

Bug: Type Inference for Nullable Union Types Inaccurate; Suggest Enabling Strict Mode #1474

Closed antoniel closed 11 months ago

antoniel commented 1 year ago

Sorting

Expected Behavior

Given the follow typescript code, I expect that tsoa infer the the return type as ´string | null´.

import { Get, Route } from '@tsoa/runtime';

@Route('inference')
export class TypeInferenceWithNullableValueController {
  @Get('keys-inference-with-nullable')
  public multiKeysInterfaceInferenceWithNullable() {
    const maybeString: string | null = Math.random() > 0.5 ? 'foo' : null;
    return maybeString
  }
}

Current Behavior

Tsoa should ideally infer its return type as string | null. However, it currently infers it solely as string, thereby omitting the null part of the union.. This behavior could lead to potential misunderstandings regarding the method's capabilities and can affect the OpenAPI documentation negatively.

Possible Solution

One possible solution to this problem is to set the typescript program that is created by MetadataGenerator as strict by default, it can be done by compilerOptions. It will improve the inference of typescript in this case and in many others without any cons as I can see.

Steps to Reproduce

  1. Create a controller that returns string | null
  2. Run tsoa on this controller to generate openApi
  3. Assets that the route was created with the response type as string, and not a union of string and null

Context (Environment)

Version of the library: 5.1.1 Version of NodeJS: 18.12.0

Detailed Description

Upon a preliminary investigation, it appears that the TypeScript program created by the MetadataGenerator is not configured to operate in strict mode. Strict mode in TypeScript enhances type checking and adds certain compile-time checks that would likely resolve this issue.

Breaking change?

It may change the output of existing definition, this change will increase the accuracy of the schemas generated by tsoa. This change will not reduce in any way the scope of existing OpenApi Schemas.

github-actions[bot] commented 1 year ago

Hello there antoniel 👋

Thank you for opening your very first issue in this project.

We will try to get back to you as soon as we can.👀

github-actions[bot] commented 11 months ago

This issue is stale because it has been open 30 days with no activity. Remove stale label or comment or this will be closed in 5 days