Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

214
Views
Prevent type conversion in JavaScript/TypeScript

I am currently learning JavaScript. I used to work with statically typed languages, so, naturally, I decided to start with TypeScript instead of JS. TypeScript is nice and it solves a lot of problems JS has, but this "weak typing" really triggers me.

It doesn't feel right that I can get away with this:

let int: number = 42
let str: string = "69"

console.log(int + str)

Is there a way to prevent this type of conversion from happening even in the TypeScript? I want to get an error when add string to an integer.

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

No, there's no rule in TypeScript that would prevent your doing that; the result of the expression int + str is string.

Now, if you tried to assign that to a variable of type number, that would fail:

let int: number = 42
let str: string = "69"

let result: number = int + str;
//  ^ error: Type 'string' is not assignable to type 'number'.(2322)

Note that this has little to do with loose typing; many strongly-typed languages such as Java and C# do exactly the same thing, implicitly convert the number to a string when using + in that way. Java example | C# example. Granted JavaScript takes this ridiculously far, but that's more about the early ethos in the language having been to prefer conversion over throwing errors. (Both probably stem from the same underlying goal, though, which was to make the language really accommodating — too much so, we now know. :-) )

about 4 years ago · Juan Pablo Isaza Report

0

Typescript as noted above doesn’t have this but Eslint does: https://eslint.org/docs/rules/no-implicit-coercion and https://github.com/typescript-eslint/typescript-eslint/blob/main/packages/eslint-plugin/docs/rules/restrict-plus-operands.md

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!