01) TypeScript
1.1 Development Environment
Official website to download
Node.js (nodejs.org)
Create a project
Initialize the first TypeScript project with a new “first-ts-project” folder
A package.json file will automatically appear in the “first-ts-project” folder
Then execute the following command to install the latest stable version of typescript
Create tsconfig. Json
Method 1: use the VScode editor
-
Create an index.ts file and open it with VScode
-
Click the TypeScript version number at the bottom of VScode
-
Click “Create TsConfG” in the pop-up box that pops up
An option prompts you to create tsconfig.js
Click Create, and it’s automatically created
After creating tsconfig.json, if you want to add a parameter to vscode, just type “” to be prompted, and hover over the parameter to be prompted
TS Playground
Method 2: Create using the command lineCreating tsconfig.json in this way includes all the compiler parameters and their descriptions
1.2 Preliminary Knowledge
TypeScript’s relationship to JavaScript
TypeScript is a superset of JavaScript
TypeScript provides all JavaScript features. And adds TypeScript’s type system on top of it
This type system is designed to be optional. This means that all legitimate JavaScript code is legitimate TypeScript code.
TS compilation process
Let’s compare the C++ compilation process to the TS compilation process
As you can see from the figure, js files are generated regardless of whether the TS file has errors. If the TS file has an error, the JS file will also report an error at runtime.
The type system
Structure type system
Structure System (Structural Type System) : by Type of practical structure to determine whether two types is equal or compatible (TypeScript, Haskell, Ocaml, Go)
Example: Create a of type Foo and assign it directly to b of type Bar;
This is fine because they have the same structure in their classes
Nominal type system
Nominal Type System: Determining whether two types are equal or not based on the Type name (Nominal Type System)
The same example would not work in a notional type system because they have different type names.
Type annotations
Types and sets
A collection for each type
Empty set never = {}
Null = {Null} Undefined = {Undefined} Literal Type(Literal Type,”a”,1,true)
Finite set Boolean = {true, false}
Infinite set String = {‘a’, ‘b’… } Symbol = { Symbol(…) . } BigInt = {… , -1n, 0n, 1n, … } Number = {-lnfinity,-(2^53 – 1),… , 0, + 2 ^ 53-1, Infinity} and NaN
The complete
Type crossing and merging
Type the alias
In JS, variables can be declared using let, const, and var
In TS, you can use type to declare aliases for types
let ID = 9527; Const PI = 3.14; var myPI = PI; Int ID = string; int ID = string; int ID = string; type User = { id:ID; name:string; } Duplicate codeCopy the code
But type has the same scope as let
Declaration in the same domain returns an error
But declaration in different fields will not report an error
The type broadens rather than Narrows
4) Type broadening (Type KP)
When you assign a literal to a let or var variable, TS does not use the literal type as the type of the variable. It broadens from literal types to correspondingly broader types.
Type Narrowing
In some cases, TS can be more specific about the type of the variable, in which case it Narrows the type.
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 type guarding, code flow analysis
When declaring a variable using let var, TS assumes that the variable will change in the future, so it extrapolates the type to a relatively broad type
When declaring a variable using const, TS knows that constants are invariant and extrapolates the type to the narrowest literal type
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.
The syntax of TS introduces values to both Spaces.
Type and interface introduce related types into the type space
Const let var introduces related variables or constants into the value space
Enum Class Namespace imports types for the type space and values for the value space
If a namespace contains only type declarations, no JS code is generated and no variables are introduced
How do you tell which space the symbol is in?
-
Symbols that disappear after translation -> type space
-
Symbols as type annotations, aliases -> type space
type T= typeof Person; const p:Person
-
Symbol -> type space after type assertion
target as/is HTMLElement
-
Const let var symbol -> value space
-
Class enum Symbol -> Value space + type space of namespace
There are also operators that exist in both Spaces but express completely different meanings.
typeof
Expressions following typeof can only be variables, not types
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’)
In type space, Typeof returns the TypeScript type corresponding to the identifier
[] Index 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
This keyword
In the value space, the this pointer is 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
Used in type space with as, that is, “as const” constant assertion, narrowing the type
Look at the following example
No as const is inferred to be of type number
Here is the result of adding as const
externds
Used in value space to define subclasses
Class A externds B{} Copies the codeCopy the code
Used in type space for type constraints or interface inheritance
T externds number interface A Externds B Replication codeCopy the code
in
Used in value space for loops and to determine if an attribute exists
The declaration of the key used to map the type in the type space
[K in T] Copy codeCopy the code
1.3 Basic Knowledge
The type hierarchy in TS
A value of a lower type can be assigned to a variable or constant of an upper type
Variables/constants of type unknown can point to any type of value
There is no variable of type never (never is an empty set)
Top and Bottom types in different languages
Type on
any
1. Any is special. It is both top type and bottom type
That is, variables/constants of type any can be assigned to variables or constants of any type
However, the any type is insecure and has no language service, so it should be avoided as much as possible
2. Any is contagious. It makes the place it touches unsafe.
So TS introduced the type-safe unknown as the Top Type in 3.0
3. Any hides bugs
4. Any hides code design details: the design of data types is lost
So, try to avoid using any
Turn on strict mode in tsconfig
unknown
Unknown must be annotated. TS does not derive any value to unknown
The unknown type can only be equal or unequal
Only when the type is narrowed can the corresponding operation or function call be made
If the type cannot be predicted, do not use any, use unknown and narrow the type before using
boolean
Boolean types have only two elements: true/false
Let, var variables will be widened to Boolean types
Const constants correspond to literal types
It is worth noting that the combination of true and false is pushed back to Boolean
number
Number includes integer, floating point, + -infinity, NaN (not a number)
bigint
Number range [- (2 ^ 53-1), 2 ^ 53-1)
To use BigInt, you need to set the compilation options to be larger than ES2020
Bigint is a new type that can represent integers of any size
The bigint literal is a number followed by a lowercase n
Bigint supports addition, subtraction, multiplication, division, remainder, and powers
But bigint cannot be mixed with number and requires an explicit conversion
string
symbol
Variables declared by let and var are derived to type symbol
The unique symbol must be of const type
Const constants are derived into unique symbols
They can also be explicitly annotated as unique symbols
The unique symbol is not a type but a group of types. For example, unique symbol B1 and unique Symbol b1x are two types
The first argument to Symbol is a description, not the Symbol name or ID.
Symbol.for internally maintains a dictionary that returns a new Symbol if it has not been created before, or an already created Symbol if it has.
object
Use keyof to get the key on the object type
You can use object. key to obtain the key of an Object
array
When an array is created, if the type is not specified, the TS automatically determines the type
Arrays are annotated in two ways
- T[]
- Array interface generic
tuple
A tuple is a subtype of an array. A tuple is an array in which the element type at each index bit is determined.
Because tuples are created the same way as arrays, tuples must be explicitly annotated.
enum
Enumeration itself is a mapping
Enumerations that are not explicitly assigned are automatically incremented from 0
Enumeration to integers has bidirectional mapping
There is no reverse mapping for enumerations of explicitly assigned strings
Merging of enumerations
Enumerations can be split into multiple fields and can be merged with a namespace of the same name
Constant enumeration
Constant enumerations do not create variables in value space
So references to constant enumerations are replaced with corresponding values
However, it can be controlled by the compiler option preserveConstEnum
null,undefined,void,never
Undefined = {undefiend} in JS, it should mean that the defiend is Undefined, but in fact, it is declared and no value is assigned
Null = {Null} indicates that the value is declared, Null or Null
Void in TS: function has no explicit return value
The function cannot return
In JS, void is a unary operator:
It executes the following expression,
Then return undefined unconditionally
Before ES1.3, undefined was not directly accessible!
Only void(0) is available. ES1.3 adds undefined to the Global Object.
02. TypeScript advanced
Type of operation
keyof
Keyof (index type query operator) was introduced in TS2.1.
It gets the type union for all known, public keys on the type
Indexes can be number, string, symbol, but symbol is not yet supported and will be after TS4.4
This means that keyof can only query interface keys or keys similar to class
For ordinary strings, there is no need to use keyof for the number type
There are keys and values in the interface
Key exists type, can be string, number, symbol (symbol will be supported after TS4.4)
Values have types, which can be all types
interface
Interface and type aliases can be thought of as two syntaxes of the same concept
The difference between interface and type aliases
- Type aliases are more general and can contain type expressions (type union, type crossing, conditional type) on the right side, but only some kind of structure ({… })
- When extending between interfaces (extends), TS checks the relationship. However, TS will try its best to avoid errors in type union
- Multiple interface declarations with the same name in the same scope are merged, but multiple type aliases report an error
Class class
Class is a new feature introduced in ES2015
So this is just how do you describe a class using an interface
Use interface to describe a class
-
Describes the types of attributes in a class
-
Describes a function in a class
- Parameter type
- Return value type
03. Senior TypeScript
Type of operation
Mapping type
A mapping type is a way of creating object types