Home > Mobile >  Prevent type conversion in JavaScript/TypeScript
Prevent type conversion in JavaScript/TypeScript

Time:06-18

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.

CodePudding user response:

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. :-) )

CodePudding user response:

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

  • Related