Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”
At the same time, I participated in the Digitalstar project to win the creative gift package and challenge the creative incentive money
preface
Bugs in our system programs are called bugs. The world’s first bug, is 1946 Hope discovered the first computer bug, turned out to be a moth “bedbug”. The process of solving these problems is called bug catching, debugging, or debugging.
Preparing for development Environment
There are many detailed installation tutorials available online!
Install VSCode
Installation Node. Js
Create a project
Initialize a TypeScript project
Create a [first-ts-project] folder, go to the folder, and execute on terminal
npm init -y
Copy the code
You can create one in your folderpackage.json
fileThe latest stable version of typescript
npm install -- save-dev typescript
Copy the code
The latest typescript
npm install --save-dev typescript@next
Copy the code
Create tsconfig. Json
Method 1: Create an index.ts file in the VScode editor and open it with VScode. Click on the TypeScript version number at the bottom of VScode and click create tsconfg in the pop-up box.
{
"compilerOptions": {
"module": "commonjs",
"target": "es2020",
"jsx": "preserve",
"strictFunctionTypes": true,
"sourceMap": true
},
"exclude": [
"node_modules",
"**/node_modules/*"
]
}
Copy the code
Method 2: Use the command line
node_modules/.bin/tsc --init --locale zh-CN
Copy the code
Created this waytsconfig.json
Contains all compiler parameters and parameter descriptions
tool
TS playground
TS Playground
Equal<X, Y>
Equal<X, Y>
Preliminary knowledge
TS and JS
-
TypeScript is a superset of JavaScript
-
TypeScript provides all JavaScript features. And adds the TypeScript type system on top of it.
-
The type system is designed to be “optional,” which means that all legitimate JavaScript code is legitimate TypeScript code.
TS compilation process
-
‘TS type checking’ and ‘JS generation’ are two separate processes;
-
Type checking errors do not affect generating JavaScript code;
The type system
Structural Type systems determine whether two types are equal or compatible by their actual structure
TypeScript, Haskell, OCaml, Go,...
Copy the code
Nominal Type System Determines whether two types are equal based on the Type name
C, C++, Java, C#, Rust,...
Copy the code
TS uses the structure type system
Structure type system
// struct type system: OK class Foo {public hi() {console.log('hi'); } } class Bar() { public hi() { console.log('Hello'); } // assign an instance of Foo to a const a: Foo = new Foo(); // assign a to b const b: Bar = a; // call the hi() method on b. //Works!Copy the code
Nominal type system
Class Foo {public: void hi() {STD ::cout << "hi" << STD ::endl; }}; class Bar { public: void hi() { std::cout << "Hello" << std::endl; }}; int main() { Foo foo; Foo &fooRef = foo; //Error: Type 'Bar' cannot // Bind to a value of 'Foo' // Assign the variable Foo to the Bar reference, and during the assignment, the compiler will report an Error because the two types are completely unrelated. Bar & Bar = foo; return 0; }Copy the code
Type annotations
Contrast: type annotation syntax in different languages
C++ first
int printf(const char*,...) ;Copy the code
Objc comes first, parentheses
- (id)initWithInt:(int)value;
Copy the code
Julia at the end, double colon
commission(sale::Int,rate::Float64)::Float64
Copy the code
The type annotation for TS follows with a single colon
function log(message: string): void
Copy the code
The relationship between types and collections
- Empty Set (Empty Type)
Never = ∅ = {}Copy the code
- Set of elements (Unit Type)
Null = {Null} Undefined = {Undefined} Literal Type(Literal Type,"a",1,true)Copy the code
- Collection co., LTD.
Boolean = {true, false}
Copy the code
- Infinite set (approximation)
String = {a','b',... ,'hello',... } Symbol = {Symbol(...) . } BigInt = {... ,-1n, 0n, 1n,... } Number = {-Infinity,-(2^53 - 1.),... 0,... ,+2^ 253-1,Infinity} and NaNCopy the code
- Universal Set
Type union and crossover
Type the alias
Analogy:
-
In JS: you can declare variables or constants using let, const, var
-
In TS: You can use type to declare aliases for types
Can be interpreted as the name of “something”, which is easy to remember and more descriptive.
// let ID= 123; Cconst PI = 3.14; var myPI = PI; //TS alias for the type declaration type ID = string; type User = { id:ID; name:string; }Copy the code
Knowledge:
- Type aliases are similar to let variables in that they have block-level scope. Therefore, the same name cannot be in the same scope.
type User = {
id:ID;
name:string;
}
type User = { }
Copy the code
- The inner type alias hides the outer type of the same name
type User = { id:ID; name:string; } // block level scope {type User = {id: id; nname:string; }}Copy the code
The types are broadened and narrowed
4) Type broadening (Type KP)
When you assign a literal to a let or var variable, TS does not use a literal type (a collection of elements) as the type of the variable. It broadens from literal types to correspondingly broader types. This process is called type broadening.
Type Narrowing
In some cases, TS can be more specific about the type of the variable, in which case it Narrows it down.
Knowledge:
-
TS tries to strike a balance between type certainty and flexibility
-
TS provides a number of methods to help narrow types to improve type determinism:
Null Check, as const, Instanceof, Typeof, attribute checking, Tagged Union, User-defined Type Guard, code flow analysis
-
When a variable is declared with let var, TS believes that the variable will change in the future, so the type is inferred as a relatively broad type
-
When a const is declared as a constant, TS knows that the constant will not change and extrapolates the type to the narrowest literal type
On the left isType to broadenOn the right is theType narrowing
Value space and type space
-
The type space is created by the TS compiler, TSC, and contains various types. TSC instantiates various types based on code.
-
The value space is created after JSEngine and contains various runtime values.
How do you tell which space the sign is in?
-
Symbols that disappear after translation → type space
-
Symbols as type annotations, aliases → type space (type T = typeof Person; T is in the type space const p: Person; T is in type space.
-
Symbol after type assertion → type space (Target as/is HTMLElement; The symbol after as/is is in the type space.
-
Const, let, var symbol → value space
-
Class, enum, symbol after namespace → value space + type space
In addition, there are some operators that exist in both Spaces but have completely different meanings:
typeof
In the value space, Typeof returns a string representation of the JavaScript type corresponding to the following expression:
'string', 'number', 'bigint', 'boolean', 'symbol', 'undefined', 'object', 'function'
Copy the code
In type space, Typeof returns identifiers corresponding toTypeScript type
[](Indexed Access Operator Indexed Access Operator)
-
In the value space, val[field] or val.field returns the value of the property corresponding to val
-
In Type space, Type[T] returns the TS Type corresponding to T
Symbol and Template string pattern were added after TS4.4
This keyword
-
In value space, this refers to… More complicated
-
In type space, this can be used as the return value of a class method to implement chained calls
& | operator
-
Represents Bitwise AND AND Bitwise OR in value space
-
Represents the intersection and union of types in type space
const
-
Used to declare constants in the value space
-
In type space with as, that is, “as const” constant assertion, narrowing the type
extends
-
Used to define subclasses in value space (class A extends B)
-
Used in the type space for type constraints (T extends Number) or interface inheritance (interface A extends B)
in
-
In value space for loop (for (key in object) {… }) and check whether the attribute exists (‘name’ in person)
-
Declarations (Mapped Types) for keys used to map types in Type space
conclusion
If there is any mistake above, please point out in the comment section, thank you!
After reading it, give it a thumbs-up and then walk away