简体   繁体   中英

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 .

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

上面提到的打字稿没有这个,但 Eslint 有: https ://eslint.org/docs/rules/no-implicit-coercion 和https://github.com/typescript-eslint/typescript-eslint/blob/main /packages/eslint-plugin/docs/rules/restrict-plus-operands.md

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM