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