In TypeScript, values other than numbers or strings can be accepted as parameters, even when the expected type is a

The issue I am encountering with TypeScript is quite perplexing, especially since I am new to this language and framework. Coming from a Java background, I have never faced such a problem before and it's presenting challenges in my bug-fixing efforts with TypeScript / NestJS.

It appears that there may be a lack of type safety in TypeScript, which raises questions about whether it functions as intended or if there is a specific reason for this behavior. Below is a simplified example to demonstrate the issue:

  async findAll(@Query() query, @Res() res: Response) {
      ... lines omitted ...
      this.cache.getProxyCache(query.page, query.page_size);
      ... lines omitted ...
  }

The query object obtained from the @Query decorator in a NestJS controller is causing confusion.

  async getProxyCache(page: number = 0, pageSize: number): Promise<AxwayProxy[]> {
    console.log(`page: ${page} typeof: ${typeof page}`);
    console.log(`pageSize: ${pageSize} typeof: ${typeof pageSize}`);

    let pageSizeAdded = pageSize + 3;
    console.log(`pageSizeAdded: ${pageSizeAdded} typeof: ${typeof pageSizeAdded}`);

    let pageSizeAdded2 = Number(pageSize) + 3;
    console.log(`pageSizeAdded2: ${pageSizeAdded2} typeof: ${typeof pageSizeAdded2}`);
    ... lines omitted ...

The output reveals a discrepancy, particularly in the value of pageSizeAdded, which is incorrect. On the other hand, pageSizeAdded2 is calculated accurately after converting the data type from string to number:

page: 1 typeof: string
pageSize: 4 typeof: string
pageSizeAdded: 43 typeof: string
pageSizeAdded2: 7 typeof: number

I find it puzzling that both page and pageSize are being treated as strings even though they are declared as numbers in the function parameters.

While TypeScript displays an error message when attempting to directly call the function with string values (e.g.,

this.cache.getProxyCache('1', '2');
), it seems to accept non-number values when passed from another object.

Has anyone else encountered this issue? Is it a known limitation or a bug? Why is this behavior permitted?

Thank you, Christoph

Answer №1

It is important to note that TypeScript will be converted into JavaScript before it is executed. This means that all the typing information will be removed. When you define a function like

async getProxyCache(page: number = 0, pageSize: number): Promise<AxwayProxy[]>

You are essentially asking TypeScript to verify that the parameters and return type are correct. However, this verification only happens during transpilation (and in development with a good IDE). At runtime, the types are no longer enforced, allowing you to pass any value without any checks or casting. The resulting code in pure JavaScript will look like this:

async getProxyCache(page = 0, pageSize)

If you are wondering why TypeScript allows you to call the function with values that are not numbers, consider checking the type of page where the function is being called. If it is declared as any, then it is compatible with any type. In this scenario, it might be better to declare it as unknown instead, which would require explicit type-checking before usage.

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

An issue arises in VueJS when employing brackets and the replace function in Typescript

My journey with the Typescript language has just begun, and I am excited to dive deeper into it. Currently, I am working on a SPA-Wordpress project as a hobby using Vite (VueJS). However, I am facing some challenges with the syntax when transitioning from ...

Working with intricately structured objects using TypeScript

Trying to utilize VS Code for assistance when typing an object with predefined types. An example of a dish object could be: { "id": "dish01", "title": "SALMON CRUNCH", "price": 120, ...

Find the identifier that does not currently exist in the collection of objects

There is a situation where I have an array and an object that consists of arrays of ids, which are essentially permission objects. My goal now is to extract the ids that do not exist in the given object. Can someone assist me with devising the necessary l ...

How to utilize methods from different pages in Ionic 2

Looking to display the total number of items in an array on a card located on the home screen, but facing issues referencing methods outside of the typescript file they're written in. Trying to extract the array size method and utilize it in a differe ...

Integrating Octokit middleware in Next.js for enhanced functionality

Currently, I am in the process of honing my skills by creating a GitHub app. In Octokit, there is a feature called createNodeMiddleware that caught my attention. However, integrating it with next.js seems to pose some challenges. My main issue right now re ...

Protractor experiencing difficulty recognizing Angular functionality

Recently, I made the switch to using Protractor for running end-to-end tests on my Angular application. However, the e2e tests have suddenly started failing because Protractor is unable to detect Angular on the website. I raised this issue in their GitHub ...

The Server Components render encountered a glitch

Screenshot of the errorI am encountering a strange error only in the production environment. The lack of additional information leads me to believe it may be due to security measures put in place for production. Unfortunately, I have been unable to repli ...

Encounter issue with async function in produce using Immer

Having an issue while attempting to create an asynchronous produce with immer. When calling the async function, this error is encountered: Below is my code snippet: import { combineReducers, createStore } from 'redux'; import produce from ' ...

Warning: Potential spacing issues when dynamically adjusting Material UI Grid using Typescript

When working with Typescript, I encountered an error related to spacing values: TS2322: Type 'number' is not assignable to type 'boolean | 7 | 2 | 10 | 1 | 3 | 4 | 5 | 6 | 8 | "auto" | 9 | 11 | 12'. No lint errors found Version: typesc ...

Playing around with Segment Analytics testing using Jest in TypeScript

I've been struggling to write a unit test that verifies if the .track method of Analytics is being called. Despite my efforts, the test keeps failing, even though invoking the function through http does trigger the call. I'm unsure if I've i ...

Express middleware generator function causing a type error

I recently implemented a function that takes a middleware function, wraps it in a try-catch block, and then returns the modified middleware function. tryCatch.ts import { Request, Response, NextFunction } from "express"; export default function ...

Is it feasible to utilize math.max with an array of objects?

When it comes to finding the largest number in an array, solutions like this are commonly used: var arr = [1, 2, 3]; var max = Math.max(...arr); But how can we achieve a similar result for an array of objects, each containing a 'number' field? ...

Determine if a variable contains only one digit in Angular 6 using Typescript

I have a specific value that I want to discuss: this.value.day It gives me a numerical output ranging from 1 to 31. My requirement is to add a leading zero if the number is less than 10. Can anyone guide me on achieving this? ...

The TypeScript error message states that a value of 'undefined' cannot be assigned to a type that expects either a boolean, Connection

I've been grappling with this code snippet for a while now. It was originally written in JavaScript a few months back, but recently I decided to delve into TypeScript. However, I'm struggling to understand how data types are properly defined in T ...

Can you explain the functionality of `property IN array` in the TypeORM query builder?

I'm looking to filter a list of entity ids using query builder in an efficient way. Here's the code snippet I have: await this._productRepo .createQueryBuilder('Product') .where('Product.id IN (:...ids)', { ids: [1, 2, 3, 4] ...

What is the best way to change `props.children` into a JSX element?

When using React functional components, we have the ability to render children in the following way: import React from 'react'; const MyComponent = (props: React.PropsWithChildren) => { return props.children; } However, I encountered an ...

In Certain Circumstances, Redirects Are Applicable

I have set up Private Routing in my project. With this configuration, if there is a token stored in the localStorage, users can access private routes. If not, they will be redirected to the /404 page: const token = localStorage.getItem('token'); ...

The MatInput value will only display after the page is reloaded or refreshed

After refreshing the page, a matInput field displays a value or result that was previously hidden. https://i.stack.imgur.com/q9LQI.png By selecting or highlighting within the matInput, the value or result becomes visible. https://i.stack.imgur.com/SqaLA.p ...

Setting up TypeScript in Node.js

A snippet of the error encountered in the node.js command prompt is as follows: C:\Windows\System32>npm i -g typescript npm ERR! code UNABLE_TO_VERIFY_LEAF_SIGNATURE npm ERR! errno UNABLE_TO_VERIFY_LEAF_SIGNATURE npm ERR! request to https:/ ...

Dynamically generating an Angular component and populating it with data

I am currently working with Angular 7/8 and I have some code that adds a new component dynamically. In the parent component, my .ts file includes the following: PARENT COMPONENT Within the .ts file: @ViewChild(InjectDirective) injectComp: InjectDirect ...