TypeScriptGet to know TypeScript

Author: Laojiu
Personal blog: Laojiu’s CSDN blog
Personal quote: Facing uncontrollable things with optimism
Series of columns:

Article directory

  • TypeScript
    • Disadvantages of Javascript
    • Refactoring using TypeScript
    • TypeScript compilation environment
      • Globally install the TS compilation environment
      • TS compilation simplified
    • TS variable declaration
      • TS variable type deduction
      • type of data
        • Javascript data types
        • TypeScript data types
      • Do the parameters of anonymous functions need to be added to the type?
      • Optional type
      • Any type
      • unknown type
      • void type
      • never type
      • array type
      • tuple type (tuple type)
    • TS function type
      • Function type writing method
      • Function parameter assignment default value
    • union type
      • shrink union
    • type alias
    • interface declaration
    • The difference between type and interface
    • readonly readonly attribute
    • EnumEnum
      • example
      • constant enumeration
      • Computed property enum
    • Generics
      • constrained generics
      • Using generics in classes
      • Using generics in interface
    • type assertion
    • TS statement document (understand)

TypeScript

Disadvantages of Javascript

function getLength(args){<!-- -->
  return args.length
}

// Call functions
console.log(getLength("aaaa"));
console.log(getLength(["abc","cba","nba"]));
//This is wrong. Normally you will see this error when writing code.
console.log(getLength(123))
console.log(getLength())

Typescript is tosolve the pain point of JavaScript’s missing type detection mechanism, because the sooner the error is discovered, the better

The order in which errors are discovered
When writing code > When compiling code > During code running > During testing > Errors are found after going online

TypeScript is a superset of JavaScript with types, and also adds some grammatical extensions (enumerations, tuples, etc.). TypeScript is eventually compiled into JavaScript, so you don’t have to worry about compatibility issues.

Refactoring using TypeScript


This way you can find errors directly while writing code.

TypeScript compilation environment

We need to write the main.ts code first, then compile the main.ts code into main.js code, and then run it on the browser
If you do not install the TS compilation environment, it does not matter for writing code, but it cannot be run on the browser because the browser only recognizes JS code.

Globally install the TS compilation environment


Test code:

//string: TS defines the identifier for us and provides the string type
//String: packaging class for strings in JS
let message : string = "Hello world"

Steps to execute ts code:
1. Compile the TS code first: tsc xxx.ts
2. Execute the js just compiled

TS compilation simplified

Two solutions

How to install ts-node?
npm install ts-node-g
npm install tslib @types/node -g
How to do it?
ts-node math.ts

Declaration of TS variables

var/let/const variable name: data type = assignment

TS variable type derivation

When declaring a variable, if there is direct assignment, the type annotation of the variable will be deduced based on the type of assignment.

Note: When the let type is deduced, the deduced type is a universal type; but when the const type is deduced, the deduced type is a literal type

Data type

Javascript data type

number: Do not distinguish between int and double, unified as number type
boolean: true and false, the simplest
String: Both single and double quotes are acceptable, and template string concatenation variables are also supported.

let name : string = "why"
let age : number = 18
let height : number = 1.88

let info : string = `my name is ${<!-- -->name} , age is ${<!-- -->age} , height is ${<!-- -->height}`
console.log(info);

export {<!-- --> };

Symbol type: Usually we cannot add the same attribute name to the object, but through symbol, we can define the same name

null type
undefined type

TypeScript data type

Array type: There are two ways of writing, the first is string[], the second is Array, if the array stores different types, use any

Object type: define the attribute type in the object through the type keyword

any type: can represent any type, similar to the Object type in Java

Do the parameters of anonymous functions need to be added types

Conclusion: It is best not to add type annotations, because TS can automatically specify the type according to the context. If we add it ourselves, we may add errors.

Optional type

Optional type, add one after the variable? , which means you can pass this parameter or not.

Any type

When we cannot determine the type of a variable and it may change, we can use the any type
The any type does not limit any type of variable, and can call any method, which is no different from writing code in JS

When to use:
When the nesting level of data returned by the server is too complex and the data types are too redundant, you can use the any keyword

unknown type

unknown is a variable of uncertain type in TS. The difference from any is that no operations can be performed on values of unknown type. For example, .length in the following code will not work

What is the use of unknown type?
unknown requires us to perform type checking (type reduction) before we can perform corresponding operations based on the reduced type; so unlike any, variables of unknown type require type checking before we can perform corresponding operations, and any has security risks; the unknown type is equivalent to the safer any type

void type

1. In TS, if a function does not have any return value, the return value type is void type.
2. When returning void type function parameters, it is best to add the parameter type, otherwise an error may be reported.
3. If the return value is void type, then we can also return undefined (generally we don’t do this)

scenes to be used:
The return value used to specify the function type is void

never type

never type application scenarios:
1. The never type is rarely actually defined in development, but in some cases type derivation will be performed automatically.
2. The never type may be used when developing frameworks or packaging tools
3. To encapsulate some types of tools, you can use never
The never type will not return anything. For example, in the case of an infinite loop, throwing an exception, etc., it will not return anything.

Array type

There is a type in front, followed by a square bracket
There can only be one type in the array. In the following code, the array can only be of type number and not other types.

Add a concept, array-like
If you create a function, the function has an argument by default, which is an array-like argument.

tuple type (tuple type)

Similar to an array, an array aggregates data of the same type, but a tuple specifies the type of each element in the array, and different types of data can be stored in an array.

TS function type

The parameters of a function can have types, and the return value of a function can also have a type.
The return value type can be specified explicitly or type derivation can be performed automatically.

type LyricType = {<!-- -->
  time : number
  text : string
}
function parseLyric() : LyricType[]{<!-- -->
  const lyrics : LyricType[] = []
  lyrics.push({<!-- -->time:111,text:"爱してる"})
  return lyrics
}
const lyricInfos = parseLyric()
for(const item of lyricInfos){<!-- -->
    console.log(item.time,item.text);
}
export {<!-- --> }

How to write function types

Because functions are also objects, you can assign functions to variables

You can also put forward the type of the function

This writing method is generally used in higher-order functions. When the parameters of a function receive another function, the parameter type of the function can be specified by writing like this. The code is as follows:

Function parameter assignment default value

If assigned a default value, it defaults to an optional parameter.

Union type

1. A type composed of two or more other types
2. Can be any value of these types

Narrow union

Infer more specific types by shrinking the structure of your code

Type alias

The keyword type just gives an alias to a type

Usage scenarios for using type aliases under union types

Interface declaration

Used to define the Object type in JS
Only for objects, it is no different from the use of type. When defining the object type, most of the time, you can choose to use
Interface is a declaration, there is no assignment equal sign like type

The difference between type and interface

1. The type type has a wider range of use, and the interface type can only be used to declare objects
2. When declaring an object, interface can be declared multiple times, but type cannot.

3.Interface supports inheritance

readonly read-only attribute

to be added in front of the variable

Enum

It is equivalent to defining a set of constants. If no value is assigned, it starts from 0 by default, similar to an array.

If the first number is assigned, then the next one is + 1

If a string is assigned, everything else must be assigned a string.

Example

Constant enumeration

Constant enumeration is used. When compiling, the code that defines the enumeration will not be compiled, but the value will be translated directly, which can improve performance.
But not all can be constant enumerations. If it is a calculated value enumeration, it will not work.

This is ts code

This is js code compiled without using constant enumerations

This is code compiled using constant enums

Computed property enumeration

Computed property enumerations allow you to specify calculated expressions for enumeration members, and these calculated expressions are evaluated at compile time. Members of a computed property enumeration can contain any expression, not just constant values.
Note: This type of enumeration cannot be preceded by const

Generics

Similar to a placeholder, T is the type of whatever type is in echo.

Generics of tuple type

Constrained generics

Requirement: Only pass in variables containing the length attribute
Implemented through extends

Using generics in classes

Requirement: Implement a queue where the type of elements pushed into the queue is the same as the type of elements pushed out of the queue.

Code explanation:

Using generics in interface

1. Used to define objects

2. Used to define functions

Type assertion

In a union type, only their common properties and methods can be accessed

Through the as keyword, you can make type assertions and tell the compiler that I know the type of the variable better than you do.

Examples of using type assertions:

Of course we have a simpler way of writing
Directly use generic writing

TS declaration file (understand)

Through the TS declaration file, you can easily use third-party JavaScript libraries in TypeScript projects.
The declaration format of the TS declaration file is xxx.d.ts

?Coding is not easy, everyone’s support is what keeps me going?
Copyright statement: This article is an original article by CSDN blogger “No. 101 of the 100 Most Handsome Faces in the Asia-Pacific Region”