当前位置:网站首页>Typescript is a weak type

Typescript is a weak type

2022-06-24 01:34:00 HoneyMoose

The type system follows 「 Whether to allow implicit type conversion 」 To classify , It can be divided into strong type and weak type .

The following code, whether in JavaScript In or out TypeScript All of them can work normally , Run time numbers  1  Will be implicitly typed into a string  '1', plus  +  Recognized as string splicing , So it prints out as a string  '11'.

console.log(1 + '1');
//  Print out the string  '11'

TypeScript It's fully compatible JavaScript Of , It will not be modified JavaScript Runtime features , therefore   They are all weak types .

Weakly typed languages correspond to strongly typed languages , for instance Java. Strongly typed language is a language that enforces type definition , That is, once a variable is defined as a type , Without coercion , Then it will always be this damn data type . Strong languages include :Java、.net、Python、C++ Other languages .

Although sometimes Java It will also give you some implicit conversions , But in most cases, the types do not match , An error will be reported when compiling .

for example , We can look at the following Python Code , because Python It's a strong type , The following code will report an error when running :

print(1 + '1')
# TypeError: unsupported operand type(s) for +: 'int' and 'str'

To fix this error , You need to cast :

print(str(1) + '1')
#  Print out the string  '11'

strong / Weak is relative ,Python When dealing with the addition of integers and floating points , Will implicitly convert an integer to a floating point , But it doesn't affect Python Is a strongly typed conclusion , Because most of the time Python There is no implicit type conversion . Compared with ,JavaScript and TypeScript No matter what type is on both sides of the plus sign , Can calculate a result through implicit type conversion —— Instead of reporting a mistake —— therefore JavaScript and TypeScript All weak types .

although TypeScript There is no restriction on the type of both sides of the plus sign , But we can use TypeScript Type system provided , as well as ESLint Code checking function provided , To restrict both sides of the plus sign to be numbers or strings . To some extent, this makes TypeScript towards 「 Strong type 」 One step closer —— Of course , This limitation is optional .

This type system embodies TypeScript Core design concept of : In complete preservation JavaScript Based on runtime behavior , Improve the maintainability of code by introducing static type system , Reduce the possibility of bug.

That's why it's right Java Let's talk about it , Maybe I prefer TypeScript some .

https://www.ossez.com/t/typescript/13810

原网站

版权声明
本文为[HoneyMoose]所创,转载请带上原文链接,感谢
https://yzsam.com/2021/11/20211117102012699f.html

随机推荐