Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

This article has participated in the “Digitalstar Project” and won a creative gift package to challenge the creative incentive money.

📢 Hello everyone, I am Xiao Cheng, a sophomore front-end enthusiast

📢 this article is a study note for learning TypeScript

📢 Thank you very much for reading

📢 May you be true to yourself and love life

1. Build an environment

Install typesctipt globally

npm i -g typescript
Copy the code

Create a TS file

console.log('Hello Ts');
Copy the code

Convert TS by command

tsc 'File name'
Copy the code

2. Basic types

Js is a dynamically typed language, so there are many times no errors, but there will be a lot of problems

1. number

Define a value of type number

let a: number
a = 10
a = 'hello' // This line of code will report an error because a is of type number and cannot be assigned a string
Copy the code

But the compilation will still work

2. string

Define a value of type string

let b: string
b = 'hello'
b = 10 // b
Copy the code

3. boolean

Assign directly after declaration

let c: boolean = true
Copy the code

TS can automatically type check variables if they are declared and assigned at the same time

let c = false
c = 123 / / an error
Copy the code

4. The literal

The value is restricted to male and female

let d: 'male' | "Female"
d = 'male'
Copy the code

5. any

Any type, which is equivalent to turning off type detection for changes and displaying any

Use TS instead of any

let e: any
e = 1
e = 'hello'
Copy the code

Declaring variables without specifying a type is set to any, implicitly any

6. unknown

Unknown indicates the unknown type, which is a type-safe any

Variables of unknown type cannot be directly assigned to other variables

let f: unknown
f = 'hello'
f = 1
f = true
Copy the code

Types of assertions

When we need to assign a variable of unknown type to a variable of another type, we can give it a type

c = f as boolean
// The second way
c = <boolean>f
Copy the code

7. Function return type

Follow the specified type after the parentheses

function sum(a: number, b: number) :number {
    return a + b
}
Copy the code

Void denotes null, indicating that no value is returned

Never: a value is never returned

8. object

// Specify the attributes that the object contains
let b: { name: string }
b = { name: 'small cheng' }
Copy the code

The object members must be identical. If there are optional attributes in the object, we can use? To deal with

let b: { name: string, age? :string }
b = { name: 'small cheng' }
Copy the code

You can do this with or without age

If you need to set any, you can use the following method

let b: { name: string, [propName: string]: any }
Copy the code

But there must be a name member

9. array

Declares an array of the specified type

let e: string[]
e = ['a'.'b']
Copy the code

You can also do it this way

let f: Array<number>
Copy the code

10. Yuan group

Fixed length array

let h: [string, string]
h = ['hello'.'asd']
h = [123.'saf'] / / error
Copy the code

11. enum

enum Gender {
    Male,
    Female
}
// Specify the enumeration type
let i: { sex: Gender }
/ / value
i = {
    sex: Gender.Male
}
Copy the code

12. & use

Here to say and mean, also can be expressed in | or oh

let j: { name: string } & { age: number }
j = { name: 'nan'.age: 20 }
Copy the code

13. Aliases for types

type myType = 1 | 2 | 3 | 4 | 5
Copy the code

Used to simplify type writing

3. Compile options

Tsconfig. json is the TS configuration file from which code can be compiled

Include represents files to be compiled, ** represents any folder, and * represents any file

"include": [
    "./src/**/*"
]
Copy the code

Specify any file in any directory under SRC

Exclude indicates a file that is excluded and does not need to be compiled. It is generally not used. The value is the same as include

Highlight compilerOptions

It’s an object that has a lot of configuration in it

1. target

Target is used to configure the compiled JS version

"compilerOptions": {
    "target": "ES3"
}
Copy the code

Here, for example, we specify that the compiled version is ES3

ES6 syntax will be demoted to ES3

2. module

The modular solution that needs to be used

"module": "ES2015"
Copy the code

There are the following optional values

'none'.'commonjs'.'amd'.'system'.'umd'.'es6'.'es2015'.'es2020'.'esnext'.
Copy the code

3. lib

Used to specify the library used by the project

"compilerOptions": {
    "target": "ES3"."module": "ES6"."lib": ["DOM"."ES6"]}Copy the code

4. outDir

Specifies the directory where the compiled file resides

"compilerOptions": {
    "target": "ES3"."module": "ES6"."lib": ["DOM"."ES6"]."outDir": "./dist"
  }
Copy the code

5. outFile

Combine the code into a file

After setting outFile, merge all global scope code into one file

Only amd and SYSTEM modular specifications can be combined

"compilerOptions": {
    "target": "ES3"."module": "ES6"."lib": ["DOM"."ES6"]."outDir": "./dist".// "outFile": "./dist/app.js"
  }
Copy the code

6. allowJS

Whether to compile JS files. The default is false

"compilerOptions": {
    "target": "ES3"."module": "ES6"."lib": ["DOM"."ES6"]."outDir": "./dist".// "outFile": "./dist/app.js"
    "allowJs": false
  }
Copy the code

7. checkJS

Whether to check whether the JS code is syntactic. The default is false

"checkJs": false
Copy the code

8. removeComments

Whether to remove comments. Default is false

"removeComments": true
Copy the code

9. noEmit

No compiled files are generated. Default is false

Only for checking grammar

"noEmit": true
Copy the code

10. noEmitOnError

Determines whether to compile when an error is reported. The default is false

"noEmitOnError": true
Copy the code

11. alwaysStrict

Used to set whether compiled files use strict mode. Default is false

"compilerOptions": {
    "target": "ES3"."module": "ES6"."lib": ["DOM"."ES6"]."outDir": "./dist".// "outFile": "./dist/app.js"
    "allowJs": false."checkJs": false."removeComments": true."noEmit": true."noEmitOnError": true."alwaysStrict": true
  }
Copy the code

12. noImplicitAny

Whether an implicit any type is allowed

"noImplicitAny": true
Copy the code

13. noImplicitThis

Whether implicit this is allowed

"noImplicitThis": true
Copy the code

14. strictNullChecks

Check for null values

"strictNullChecks": true
Copy the code

You can use

a? .bCopy the code

To correct

15. strict

Turn on all rigorous checks

"strict": true
Copy the code

All configuration

{
  "include": ["./src/**/*"].// "exclude": [],
  "compilerOptions": {
    "target": "ES3"."module": "ES6"."lib": ["DOM"."ES6"]."outDir": "./dist".// "outFile": "./dist/app.js"
    "allowJs": false."checkJs": false."removeComments": true."noEmit": true."noEmitOnError": true."alwaysStrict": true."noImplicitAny": true."noImplicitThis": true."strictNullChecks": true."strict": true}}Copy the code

Webpack TS

1. Install dependency packages

Install some dependency packages, webpack two packages recommended global installation

yarn add webpack webpack-cli typescript ts-loader
Copy the code

2. Webpack configuration file

Create a webpack.config.js file

const path = require("path");
// All configuration information is written here
module.exports = {
  // Specify the entry file
  entry: "./index.ts".output: {
    // Specify the directory to pack the files
    path: path.resolve(__dirname, "dist"),
    // The name of the packaged file
    filename: "bundle.js",},// Specify the module to use
  module: {
    rules: [{// test specifies the file in which the rule takes effect
        test: /\.ts$/,
        use: "ts-loader".exclude: /node_modules/,},],},};Copy the code

3. Modify the configuration file

In the package.json configuration file, add the build command to start the Webpack package

"scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"."build": "webpack"
  },
Copy the code

4. Introduce HTML plug-ins

Install HTML – webpack – the plugin package

yarn add html-webpack-plugin
Copy the code

The introduction of the plugin

const HTMLWebpackPlugin = require("html-webpack-plugin")
Copy the code

Configure the plug-in

 plugins:[
      new HTMLWebpackPlugin()
  ]
Copy the code

The webpack behind is not valuable, before learning, learning here is a waste of time, I suggest learning section 1

Object-oriented advice is to skip straight to abstract classes and waste time

5. An abstract class

When we don’t need this class to create objects, we can use object classes

For example, when we create Dog, we need to inherit from Animal, but we don’t need Animal to create things. To avoid it being used to create objects, we can use the abstract class abstarct

abstract class Animal {
    name: string;
    constructor(name: string) {
        this.name = name;
    }
    sayHello() {
        console.log('Animals are crying'); }}Copy the code

So we create the Animal object as an abstract class, so we can’t use it to create objects

const aaa = new Animal('sss') / / an error
Copy the code

We can add abstract methods to an abstract class without a method body

// Define abstract methods
abstract sayHello():void
Copy the code

Can only be defined in abstract classes, and subclasses must override abstract methods

6. Interface

Interface is used to define a class structure that defines which properties and methods should be included in a class

It has some similarities with Type

We can use type to describe an object type

type myType = {
    name: string.age: number
}
Copy the code

We can also use interfaces to declare a type

interface myInterface {
    name: string.age: number
}
Copy the code

We can call it normally

const obj: myInterface = {
    name: 'sss'.age: 111
}
Copy the code

The difference between interface and type at this point is that type can only be declared one time, whereas interface can be declared multiple times, for example

interface myInterface {
    name: string.age: number
}
interface myInterface {
    sex: string
}
Copy the code

In this case, the two interfaces are combined

Interfaces can be used to restrict the structure of a class when defining it

None of the attributes in the interface can have actual values. The interface defines the structure of the object, regardless of the actual values. All methods in the interface are abstract methods

Here, for example, we restrict a class that has a name and a function that says Hello

interface myInterface {
    name: string,
    sayHello(): void
}
Copy the code

Let’s write a class that implements this interface

We need to use implements to specify which interface we want to implement

class Myclass implements myInterface {
    name: string
    constructor(name: string) {
        this.name = name
    }
    sayHello() {
        console.log('good ~'); }}`
Copy the code

Define a standard in an interface that specifies that we need to implement a class. When we create a class, we need to specify the interface that it implements, using implements

7. Encapsulation of attributes

Now the properties are set in the object, and the properties can be modified at will

The data in the object becomes very insecure

We can add a modifier to an attribute

  1. publicDecorated properties can be accessed from any location
  2. privateIs defined as a private property that can only be accessed inside a class
    • Make private attributes externally accessible by adding methods to a class
  3. protectedContains attributes that are accessible only in the current class and subclasses of the current class
// Define private variables
private name: String
// Define the method of the operation
setName(value: string) {
    this.name = value
}
// Change the value of name
per.setName('pig')
Copy the code

This way, if we don’t need to change the name, we can hide the method to change the name, if we need to limit the value of the change, we can add if judgment

We can also use getters and setters to set accessors

get name() {
    return this._name
}
Copy the code

So we can get the value directly using per.name

When we need to set a value, we can use the set method

set name(value) {
    this._name = value
}
Copy the code

We can define attributes directly in the constructor, which acts as a syntactic sugar to simplify writing

constructor(public name: string.public age: number) {}
Copy the code

Is equivalent to

name: string,
age: number
constructor(name: string, age: number) {
    this.name = name;
    this.age = age;
}
Copy the code

8. Generics

When defining functions or classes, generics can be used when the type is ambiguous

First we need to add a

after the function name, to define a generic type, where the k is arbitrary, can be understood as a k type, only when the function is executed, we know exactly what type it is

function fn<k> (a: k) :k {
    return a
}
Copy the code

We can just use functions that have generics

fn(10)
Copy the code

As here we pass in a number of 10, which will automatically infer that the generic type in this function call is number

But not every time the type is automatically inferred, so we can use type assertions

Inform us in advance of the incoming data type

fn<string> ('hello')
Copy the code

We can also specify multiple generics; uppercase letters are recommended

function fn<k.t> (a: k, b: t) :k {
    return a
}
fn<string.number> ('hello'.1)
Copy the code

Specifies that the generic must be a class

interface Inter {
    length: number
}
function fn<T extends Inter > (a:T) :number {
    return a.length
}
Copy the code

Here, we set that the generic T must be an implementation class of Inter, that is, it must have the Length attribute

Use generics in classes

class MyClass<T> {
    name: T
    constructor(name: T) {
        this.name = name
    }
}
Copy the code

Learn to use TS thinking to write code, object-oriented

9. Union types

Multiple pre-types can be set

let myNumber: string | number
myNumber = 'six'
myNumber = 6
Copy the code

When multiple variables have the same type, such as the youNumber variable that also needs a string or number type, we can create a new type by rewriting the above code

type xNumber = string | number
Copy the code

This way we can use the union type whenever we need it again

let myNumber: xNumber
Copy the code

This is like an interface, and in many cases these two are interchangeable

10. Utility Types

1. Partial

When we need to use a type but want the parameters to be optional

We can go partial

type Person = {
    name: string.age: number
}
const myName: Partial<Person> = {age: 20}
Copy the code

All optional

Implementing Partial Principle

type Partial<T> = {
    [P inkeyof T]? : T[P]; }Copy the code

How do you understand that?

First T receives an object, which is the Person that we passed in above, from which T represents the Person object, and what keyin T does is it takes the key out of T, so what you get here is a combination of name and age.

(P in XXX) (P in XXX) (P in XXX) (P in XXX) (P in XXX) (P in XXX) (P in XXX) The: character indicates an optional type

2. Omit

Deletes a type from a specified type. these operations do not affect the original type

For example, we define a Person type

type Person = {
    name: string.age: number
}
Copy the code

However, when we use it in certain cases, we must pass age, and the name value is optional

We may Omit anything and the second parameter indicates the type to be removed

const myName: Omit<Person,'name'> = {age: 20}
Copy the code

Realize the principle of

Keyof T specifies the combined type of the key name. K specifies the type to be deleted. Exclude K and Pick the remaining types

Pick<T, Exclude<keyof T, K>>
Copy the code

3. Pick

Select a few types from the union types

type Person = {
    name: string.age: number
}
const myName: Pick<Person, 'age'> = { age: 20 }
Copy the code

4. Exclude

Remove several types from the union type

type Person = {
    name: string.age: number
}
const myName: Exclude<Person, 'age'> = { age: 20 } / / an error
Copy the code