TypeScript is also a language designed to solve problems with Javascript’s type system. TypeScript makes code much more reliable
Strong vs. Weak (Type safety)
Strong typing: A language-level restriction that a function’s argument type must be the same as its argument type. Weak typing does not have this restriction. For example:
// Define the line parameter name as string, then the call must pass the value of string, otherwise the compilation will not pass
const hello = (name: string) = > {
console.log(`Hello, ${name}`)
}
hello('typescript')
Copy the code
Variable types vary freely, not by strong and weak types. In my opinion, the difference between strong and weak types is that strong types do not allow arbitrary implicit type conversions, while weak types are allowed, such as weak type js:
// Automatically converts string 100 to a number
console.log('100' - 10) / / 90
Copy the code
For example, strong ts:An error was reported at compile time.
Static typing vs. dynamic typing (type checking)
A static type, which cannot be changed after a variable has been declared. A dynamic type is determined at run time and can change at any time
let a = 1 // A is a number
a = 'coffee' // At this point a becomes a string again
Copy the code
Because the way to think about it is, in a dynamic language, variables are untyped, and the values they hold are typed
Weak type problems
- Problems may not be discovered until run time
let obj = {};
obj.foo(); // TypeError: obj.foo is not a function
Copy the code
Just imagine if obj.foo() was set in a settimeout for a few hours and then executed. Function functionality changes due to type uncertainty
function sum(a, b) {
return a + b;
}
console.log(sum(100.200)); / / 300
console.log(sum('100'.200)); / / 100200
Copy the code
- Incorrect use of an object indexer
const obj = {}
obj[true] = 100 // Attribute names are automatically converted to strings
console.log(obj['true']) / / 100
Copy the code
Javascript is a weakly typed language. Why wasn’t IT originally designed as a strongly typed language? Because early JS application is relatively simple, did not expect the front-end will develop to today, and JS is a scripting language, there is no compilation stage
The advantage of strong typing
- Strongly typed code errors are exposed earlier because problems are discovered at compile time
- Strongly typed code is smarter, codes more accurately, and development tool intelligence tips are TS friendly
- Refactoring is more reliable. If you change the name of a method, you will find that all files that call the method will report an error, making it easy to locate the problem
- Reduces unnecessary type judgments at the code level
Weak js types must apply a series of judgments to ensure that they are of type number
function sum (a, b) {
if (typeofa ! = ='number' || typeofb ! = ='number') {
throw new TypeError('arguments must be a number')}return a + b
}
Copy the code