What causes TS2322 to only appear in specific situations for me?

I have been trying to create HTML documentation for my TypeScript project using Typedoc.

Within one of the many files, there is a snippet of code:

public doSomething(val: number | undefined | null | string): string | undefined | null {
  if (val === null || val === undefined || typeof val === 'string') {
    return val;
  }
  ...

While WebStorm does not show any errors and indicates that val in the return statement is of type string | null | undefined, Typedoc encounters an issue during compilation. The error thrown states:

TS2322: Type 'string | number' is not assignable to type 'string'.
Type 'number' is not assignable to type 'string'.

This discrepancy between Typedoc's analysis and the actual behavior of the application when run with nx serve raises questions about how Typedoc processes type assertions. How can I address this issue and ensure consistency across our development environment?

Although I could make changes to this specific section of code, relying on Typedoc without ensuring compatibility across our team poses challenges given our large group of developers.


UPDATE: Despite setting the module's target to es2020 initially, switching to es2022 did not resolve the Typedoc compilation error or impact the nx serve build process.

Interestingly, copying and pasting the same function elsewhere in the codebase allows Typedoc to compile it without issues. While a local typedoc.config.json file exists, it only references the main configuration file and specifies local entry points.

Answer №1

Hello, I am the maintainer of TypeDoc.

When running nx serve, it does not conduct any type checking. You can test this by intentionally adding a simple type error like parseInt(1), and then compiling.

Webstorm utilizes the compiler API on occasions. The developers believed that they could improve upon TypeScript's type inference abilities. However, in intricate projects, the results may not consistently align with what is produced by tsc. Consequently, Webstorm's output should not be solely relied upon.

TypeDoc depends on the TypeScript compiler API for performing type checking, rather than doing it autonomously. Therefore, any TypeScript errors flagged by TypeDoc should be reproducible by using

npx tsc --noEmit --project path/to/tsconfig.typedoc.json
. If this is not the case, please report it as a bug.

To pinpoint the issue you are experiencing without certainty requires a reproducing scenario. It is possible that other compiler errors are triggering a domino effect leading to the reported error. For instance, unreachable code can result in such errors.

declare function bar(x: number): void;

function foo(x: string | number) {
    if (true) {
        return x;
    }
    // Unreachable code detected.(7027)
    // Argument of type 'string | number' is not assignable to parameter of type 'number'.
    //  Type 'string' is not assignable to type 'number'.(2345)
    bar(x);
}

Answer №2

(Disclaimer: Although this answer was written before the more comprehensive response by @Gerrit0, it may still offer some useful insights)

In case you find yourself in a situation where other solutions have failed and you need a quick fix, TypeDoc has an option to bypass type checking:

typedoc --skipErrorChecking

It is worth noting that using this workaround could potentially result in crashes. As a preferable alternative, consider referring to the other answer for a more stable solution.

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

A guide to simulating Custom Dialog in Angular for Unit Testing with Jest

Currently, I am in the process of creating test cases for unit tests and ensuring code coverage for a method that triggers a dialog component when isEdit = 'true' which is retrieved from localStorage. The issue arises with the first test case wh ...

Display the new data from an array that has been created following a subscription to Angular Firestore

I am struggling to access the content of a variable that holds an array from a Firebase subscription. The issue I am facing is that I am unable to retrieve or access the value I created within the subscription. It seems like I can only use the created valu ...

To subscribe to the display of [Object Object], you cannot use an *ngIf statement without being inside an *ngFor loop

In my angular Quiz project, I have a functionality where every user can create quizzes. I want to display all the quizzes that a logged-in user has completed. Here is how I attempted to achieve this: // Retrieving user ID and category ID inside Re ...

Solving TypeScript Error in React for State Destructuring

Recently, I've been working on creating a React component for AutoComplete based on a tutorial. In my development process, I am using Typescript. However, I encountered an issue while trying to destructure the state within the render suggestions metho ...

Looking for a button that can be toggled on and off depending on the input fields

Even after adding useEffect to my code, the button component remains disabled unless the input fields are filled. It never enables even after that. export default function Page() { const [newPassword, setNewPassword] = useState(''); const [conf ...

Eliminating empty elements from arrays that are nested inside other arrays

I am facing a challenge with the array structure below: const obj = [ { "description": "PCS ", "children": [ null, { "name": "Son", ...

Error thrown by webpack: Module 'pug' not found when attempting to access get-api

After setting up webpack in express, a new folder was created. When I try to run bundle.js, it shows the message "server is running on port 3000". However, when I access the API at http://localhost:3000/api/test, the whole bundle.js loads in the console an ...

Leveraging the OpenLayers Map functionality within an Angular service

I am curious to learn if there is a way to utilize a service in Angular for creating an OpenLayers map and then passing that service to other components to update the map based on interactions within those components. I have outlined my approach below. Des ...

RxJS - Only emit if another source does not emit within a specified time frame

Imagine having two observables. Whenever the first one emits, there should be a 2-second pause to check if the other observable emits something within that timeframe. If it does, then no emission should occur. However, if it doesn't emit anything, the ...

Retrieve a specific category within a method and then output the entire entity post adjustments

I need to sanitize the email in my user object before pushing it to my sqlite database. This is necessary during both user creation and updates. Here's what I have so far: export const addUser = (user: CreateUser) => { db.prepare(sqlInsertUser).r ...

Securing Your Next.js Web App with Session Authentication

I have encountered a challenge while integrating NextAuth authentication into my React.js web application. To ensure seamless user authentication across the entire app, I am attempting to wrap a SessionProvider around the root component. However, VSCode ...

How to apply a single pipe to filter columns in Angular 2 with an array of values

I need to sort through an array of objects using multiple array string values. Here is an example of how my array of objects looks like: [{ "name": "FULLY MAINTAINED MARUTI SUZUKI SWIFT VDI 2008", "model": "Swift" }, { "name": "maruti suzuki ...

What is the best way to restrict the number of iterations in ngFor within Angular HTML

I want to use ngFor to display a maximum of 4 items, but if the data is less than 4, I need to repeat the loop until there are a total of 4 items. Check out this example <img *ngFor="let item of [1,2,3,4]" src="assets/images/no-image.jpg" styl ...

How come I am unable to fetch classes and enums from a namespace?

When using Typescript with pg-promise, I am facing an issue where I can't import the classes and enums as I normally would. Typically, when working with a library, I import a type, use it, and everything functions properly. However, in the snippet bel ...

Updating the alignment between two input mat-select in Angular materialAlternatively:Fine-tuning the reference between

I am currently working on an Angular 6 app: I have two mat-select inputs that I want to connect in a way that if the selected option in my First select is equal to the value 'AAA', then the Second select should be hidden. First Mat-Select -> & ...

Combine the selected values of two dropdowns and display the result in an input field using Angular

I am working on a component that consists of 2 dropdowns. Below is the HTML code snippet for this component: <div class="form-group"> <label>{{l("RoomType")}}</label> <p-dropdown [disabled] = "!roomTypes.length" [options]= ...

Limiting the Rate of Requests to a TCP Server using net.Server

I've been utilizing net.Server as my TCP server. Is there a way to impose a message rate limit? I managed to find solutions for enforcing rate limits in Express (express-rate-limit) and Websocket (websocket-rate-limit), but nothing specifically for ...

Transform webservice data into TypeScript object format, ensuring mapping of objects from capital letters to camel case

Something peculiar caught my attention in my Angular2 TypeScript project. When objects are fetched from a web service, they have the type "Level" and the properties are in Pascal case. However, during runtime, I noticed that the properties of these Levels ...

Having trouble retrieving information from Node.js service in AngularJS 2

I am currently expanding my knowledge of Angular and attempting to retrieve data from a node js service using Angular 2 services. When I access the node js services directly from the browser, I can see the results. However, when I attempt to fetch the dat ...

Using NestJS to import and inject a TypeORM repository for database operations

This is really puzzling me! I'm working on a nestjs project that uses typeorm, and the structure looks like this: + src + dal + entities login.entity.ts password.entity.ts + repositories ...