“Don’t be afraid, don’t settle, work hard in the future” — Hello! I am little sesame 😄
Understand a concept before you begin
Type comments:
- Function: Equivalent to type declarations in strongly typed languages, which can constrain variables
- Syntax: (variable, function): type
- Example:
let hello: string = 'hello'
First, basic data types
1. Number type
- In addition to supporting decimal and hexadecimal literals, TypeScript also supports binary and octal literals introduced in ECMAScript 2015.
let decLiteral: number = 6; / / decimal
let hexLiteral: number = 0xf00d; // Hexadecimal
let binaryLiteral: number = 0b1010; / / binary
let octalLiteral: number = 0o744; / / octal
Copy the code
2. String type (string)
let name: string = 'Little Golden Sesame'
Copy the code
3. Boolean type (Boolean)
let isGirl: boolean = true
Copy the code
Null and undefined
- By default
null
andundefined
Is a subtype of all types.
- in
tonfig.json
In the file--strictNullChecks
Set to true flag (default is false)null
andundefined
Can only be assigned tovoid
And each of them.
- Conversely, we can put
null
andundefined
Assigned tonumber
orstring
And other types of variables.
let u: undefined = undefined;
let n: null = null;
Copy the code
5, Symbol type
Symbol became the new primitive type after ES2015, so when using Symbol, you must add the es6 compiler helper library as follows:
"lib": ["es6"."dom"]
Copy the code
Note: TS recognizes compilation by default if lib is not written, but if lib is written it must specify all auxiliary compilation libraries to use, otherwise the compilation will fail
let only: Symbol = Symbol(18)
Copy the code
6. BigInt
BigInt
Type is built into TypeScript3.2 and is usedBigInt
Large integers can be safely stored and manipulated, even if the number is outside the JavaScript constructorNumber
A safe integer range that can be represented.
let res: BigInt = BigInt(Number.MAX_SAFE_INTEGER)
Copy the code
Like Symbol, when using BigInt, you must add ESNext’s compilation helper library as follows:
"lib": ["es6"."dom"."ESNext"]
Copy the code
7, Array type (array)
let arr1: number[] = [1.2.3]
let arr2: Array<string> = ['1'.'2'.'3']
Copy the code
7.1 Class array types
Common class arrays have their own interface definitions: IArguments, HTMLElement, HTMLCollection, NodeListOf…
function sum(. arg:any[]) {
// IArguments are TypeScript defined types
let args: IArguments = arguments
for (let i = 0; i < args.length; i++) {
console.log(args[i])
}
}
sum(1.2.'3'.4)
Copy the code
8. Tuple types
- In TypeScript’s base type, a Tuple represents a known type
The number of
andtype
An array of
let point: [number.number]
point = [100.100] // Compilation succeeded
point = [100.'10'] // Compilation failed because '10' is not a number type
let person: [string.number] = ['Little Golden Sesame'.18]
Copy the code
tuples | An array of |
---|---|
Each term can be of a different type | Everything is of the same type |
There is a predefined length | There is no length limit |
Used to indicate a fixed structure | Used to represent a list |
Tuples inherit from arrays, but have stricter type checking than arrays.
- Tuple out of bounds problem:
- TS allows you to insert new elements into a tuple’s push method that uses an array:
const point: [string.number] = ['0'.1]; point.push(4); console.log(point); // Output result ["a", 1, 2] Copy the code
- An error is reported when accessing a newly added element:
9, Enumeration type (enum)
Enumeration types are used to define collections of values
- Consider all possible values for a variable beforehand, and try to represent each value with a pronoun in natural language
- Such as gender (male and female), month (1-12), Day (Monday-Sun), color (red, orange, yellow, green, blue, indigo, purple)…
9.1 Enumeration
- When we declare an enumerated type, their values are actually numeric types that are accumulated from 0 by default;
enum Direction {
Up,
Down,
Left,
Right
}
console.log(Direction.Up, Direction.Down, Direction.Left, Direction.Right); // 0, 1, 2, 3
Copy the code
- When we assign the first value, we will also add it to the first value:
enum Direction {
Up = 1,
Down,
Left,
Right
}
console.log(Direction.Up, Direction.Down, Direction.Left, Direction.Right); // 1, 2, 3, 4
Copy the code
9.2 The nature of enumeration
Take the following enumeration as an example:
enum Gender{
GIRL,
BOY
}
console.log(` li lei is${Gender.BOY}`); // Li Lei is 1
console.log('Han Meimei is${Gender.GIRL}`); // Han meimei is 0
Copy the code
The compiled. Js file is as follows: compile tools: https://www.typescriptlang.org/play
"use strict";
var Gender;
(function (Gender) {
Gender[Gender["GIRL"] = 0] = "GIRL";
Gender[Gender["BOY"] = 1] = "BOY";
})(Gender || (Gender = {}));
console.log("\u674E\u96F7\u662F" + Gender.BOY);
console.log("\u97E9\u6885\u6885\u662F" + Gender.GIRL);
Copy the code
I believe you can see the principle very clearly, split understanding
Step 1 var Gender:
- Declare a
Gender
Variable and initial value is empty objectFunction (Gender) {… })(Gender || (Gender = {})); :
- will
Gender
Object is passed as an argument to a self-executing functionStep 3 Gender[“GIRL”] = 0:
- to
Gender
The “GIRL” property of the object is assigned to 0
Gender = { "GIRL" : 0 } Copy the code
Gender[Gender[“GIRL”] = 0] = “GIRL” :
- to
Gender
Object add a property named “0” and assign it the value “GIRL”
Gender = { "GIRL" : 0."0": "GIRL" } Copy the code
And so on…
Therefore, the ultimate Gender object should be:
Gender = {
"GIRL" : 0."BOY" : 1."0" : "GIRL"."1" : "BOY"
}
Copy the code
This is why enumerations can map forward and backward simultaneously.
Forward mapping: name => value; reverse mapping: name <=> value
9.3 Enumeration of Strings
enum Direction {
Up = 'Up',
Down = 'Down',
Left = 'Left',
Right = 'Right'
}
console.log(Direction['Right'], Direction.Up); // Right Up
Copy the code
String enumerations do not support reverse mapping
9.4 Heterogeneous Enumeration
enum BooleanLikeHeterogeneousEnum {
No = 0,
Yes = "YES",}Copy the code
We don’t usually use enumerations like this, but from a technical point of view, it works.
9.5 Enumeration of Constants
- Add one before declaring the enumeration
const
The statement
const enum Colors {
Red,
Yellow,
Blue,
}
console.log(Colors.Red, Colors.Yellow, Color.Blue)
// const becomes a constant by default
// console.log(0 /* Red */, 1 /* Yellow */, 2 /* Blue */);
Copy the code
- This avoids overhead in additional generated code and additional indirect access to enumeration members.
9.6 Types of enumerators
Enumeration members are classified as constant enumerators, const, and enumerators, computed, that need to be computed
- Constant enumerator:
- Enumerator with no initial value
- A reference to an existing enumerator
- Constant expression
enum userInfo{
a, // Enumerator with no initial value
b = userInfo.a, // A reference to an existing enumerator
c = 10 + 1 // Constant expression
}
Copy the code
Constant enumerators are evaluated at compile time and appear in the runtime as constants
- Enumerators that need to be counted:
- Some very large expression
enum userInfo{
d = Math.random(),
e = '123'.length
}
Copy the code
Enumerators that need to be evaluated are preserved at compile time and evaluated at run time
Enumerators after computed must be assigned values or they will be thrown incorrectly
9.7 Enumeration types and the types of enumerators
In some cases, both enumerations and enumerators can be used as a type
- Enumerators do not have any initial values
- Enumerators are numeric types
- 3. Enumerators are strings (entire enumerations cannot be used as types, only enumerators can be used as types)
No comparison can be made between two enums
- Enumerated type
enum A {a, b} // Enumerators do not have any initial values
enum B {a = 1, b = 2} // Enumerators are numeric types
enum C {a = 'a', b = 'b'} // Enumerators are strings
let age: A = 18 // Enumerations can be used as types
let age2: B = 18 // Enumerations can be used as types
age === age2 // ERROR because two enumerations cannot be compared
Copy the code
- Enumerator type
enum A {a, b}
enum B {a = 1, b = 2}
enum C {a = 'a', b = 'b'}
let a: A.a = 18 // Enumerators can be used as types
let b: A.b = 18
let c: B.a = 18
a === b // true Different members of the same enumeration can be compared
a === c // ERROR because two enumerations cannot be compared
Copy the code
9.8 Enumeration Merging
- We can declare enumerations separately and they will be merged automatically
enum Direction {
Up = 'Up',
Down = 'Down',
Left = 'Left',
Right = 'Right'
}
enum Direction {
Center = 1
}
Copy the code
Compiled to JavaScript, the code looks like this:
var Direction;
(function (Direction) {
Direction["Up"] = "Up";
Direction["Down"] = "Down";
Direction["Left"] = "Left";
Direction["Right"] = "Right";
})(Direction || (Direction = {}));
(function (Direction) {
Direction[Direction["Center"] = 1] = "Center";
})(Direction || (Direction = {}));
Copy the code
10. Any type (any)
- A variable declared as any can be assigned a value of any type.
let list: any[] = [1.true."free"];
list[1] = 100;
Copy the code
11. Unknown type
unknown
TypeScript 3.0 introduces new types, yesany
Type Indicates the security type.
The same | let value: any | let value: unknown |
---|---|---|
value = true; | OK | OK |
value = 1; | OK | OK |
value = “Hello World”; | OK | OK |
value = Symbol(“type”); | OK | OK |
value = {} | OK | OK |
value = [] | OK | OK |
unknown
 和Âany
The main difference isunknown
The type will be more strict: in pairsunknown
Before performing most operations on a value of type, we must perform some form of checking while onany
We do not need to do any checking before performing an operation on a value of type.- when
unknown
A type cannot be manipulated until it is identified as a type
The difference between | let value: any | let value: unknown |
---|---|---|
value.foo.bar; | OK | ERROR |
value(); | OK | ERROR |
new value(); | OK | ERROR |
value[0][1]; | OK | ERROR |
void
- In a way,
void
Type image is associated withany
Type, on the other hand, means that there is no type. When a function returns no value, it is common to see that its return value type isvoid
function warnUser() :void {
console.log("This is my warning message");
}
Copy the code
- Declare a
void
A variable of type is useless because it can only be assigned toundefined
andnull
let unusable: void = undefined;
Copy the code
13. Never type
Never is a subtype of another type, representing a value that does not occur, and no type can be assigned to the never type (except never itself). Even any cannot be assigned to never.
- An error is always thrown inside a function, preventing the function from terminating properly
function createError(message: string) :never {
// A function that returns "never" cannot have an accessible endpoint
throw new Error('error');
}
Copy the code
- Endless loops, code that never runs
function sum() :never {
while (true) {
console.log('hello');
}
// The end point can never be run
console.log('end point');
}
Copy the code
Difference between never and void
void
Can be assigned to zeronull
å’Œundefined
Type.never
Is a type that contains no values- have
void
A function that returns a value type will run properly. havenever
A function that returns a value type cannot return properly, cannot terminate, or throws an exception
Type inference and type assertion
1. Type inference
The ability to automatically derive the type of a value in a programming language, a feature found in some strongly statically typed languages
- You can take advantage of type inference if you assign at definition time
- Definition without an assignment is inferred to be of type any
In TypeScript, type inference helps provide types where they are not explicitly specified. Here’s an example
let x = 3;
x = '3' // ERROR
Copy the code
variablex
Type is inferred to be a number. This inference occurs when initializing variables and members, setting default parameter values, and determining the return value of a function.
If no assignment is made, it is inferred to be of type any and is not checked at all:
let username2
username2 = 18
username2 = 'Little Golden Sesame'
username2 = null
Copy the code
Type assertionas
- Type assertions can assign a variable of a combined type to a more specific type
- A union type cannot be asserted as a nonexistent type
2.1 grammar
Value As type or < type > value
In the TSX syntax (the TS version of the React JSX syntax) you must use the former, which is the value as type.
2.1.1 Value as type
let name: string | number;
console.log((name as string).length);
console.log((name as number).toFixed(2));
Copy the code
2.1.1 < type > value
let name: string | number;
let myName: number = (<string>name).length;
Copy the code
2.2 Limitations on type assertions
A union type cannot be asserted as a nonexistent type
let name: string | number;
console.log((name as boolean)); // ERROR
Copy the code
3. Non-null assertions!
StrictNullChecks: true
A new postfix expression operator in context when the type checker cannot determine the type! Can be used to assert that operation objects are non-null and non-undefined. Specifically, x! Null and undefined are excluded from the x range.
interface Entity {
name: string;
}
function processEntity(e? : Entity) {
let s = e.name; // ERROR
}
Copy the code
On the case:e
Is an optional parameter, so it may not be transmittede
The value ofundefined
, undefined
Then callname
It throws an exception
At this point we just need to add! You can avoid mistakes
interface Entity {
name: string;
}
function processEntity(e? : Entity) {
lets = e! .name;// Assert that e is non-null and access the name attribute
}
Copy the code
reference
[1]. The TypeScript’s official website
[2]. TypeScript Chinese
[3].typescript Tutorial