preface


TypeScript is a superset of JavaScript and can be understood as an upgraded version of JavaScript. JavaScript is a dynamically typed language, which makes coding more efficient and easier to write. However, it also causes difficulty in maintenance and makes it difficult for us to find errors in time when writing. TypeScript, as its name suggests, is a statically typed language that addresses the pitfalls of dynamic typing.

TypeScript doesn’t run directly in a browser; it needs to be compiled by a compiler into JavaScript, which runs in the browser. TypeScript is written in Node, so TypeScript needs to run in the Node environment. NPM I typescript-g installs TypeScript conversion to the JavaScript compiler. To convert a TS file to a JS file, simply run TSC XXX.ts

Note: TypeScript is indeed more difficult to write than JavaScript, but you’ll appreciate it over time, and the more you use it, the more you like it.

Basic types of


  • Type declaration

    • Type declarations are a very important feature of TS

    • Type declarations allow you to specify the type of ts variables (parameters, parameters)

    • When a variable is assigned a type, the TS compiler automatically checks if it matches the type declaration. If it does, the value is assigned. If it does not, an error is reported

    • Grammar:

      • letVariable: type;letVariable: type = value;letVariable = value;// Equivalent to the let variable: the type of the initial value = value;
        
        function fn(Parameter: TypeType) :{... }Copy the code
  • Automatic type judgment

    • Ts has an automatic type determination mechanism
    • When a variable is declared and assigned simultaneously, the TS compiler automatically determines the type of the variable
    • If your variable is declared and assigned at the same time, omit the type declaration
  • Type:

    type example describe
    number 1. 2.2. -21 Any Numbers
    string ‘yzy’ Arbitrary string
    boolean True, false, True or false
    literal In its own right The value of the constraint variable is the value of the literal
    any * Any type
    unknown * Type safe any
    void No value (undefined) There is no value
    never There is no value It can’t be any value
    object {name: ‘yzy’} Arbitrary JS object
    array [1, 2, 3] Arbitrary JS array
    tuple [4, 5] Element, ts new type, fixed length array
    enum Enum{A, B} Enumeration, ts new type
  • number

    • let num: number = 6
      let num2: number
      num2 = 222
      Copy the code
  • string

    • let name: string = 'yzy'
      let last_name: string
      last_name = 'tmac'
      Copy the code
  • boolean

    • let ishow: boolean = false
      let loading: boolean
      loading = true
      Copy the code
  • literal

    • let yzy: 'yzy'
      yzy = 'yzy' // The variable yzy can only be 'yzy'
      
      let sex: 'male' | 'female'
      sex = 'female' // The variable sex can be 'male' or 'female'
      Copy the code
  • any

    • let field: any
      field = 10
      field = 'x'
      field = false
      
      let name: string
      
      name = field // No error will be reported
      Copy the code
  • unknown

    • let field: unknown
      field = 10
      field = 'x'
      field = false
      
      let name: string
      
      name = field / / complains
      
      // Use an assertion that tells the program that the value's actual type is string.
      // Note that the true value of field is not a string, but this defeats the point of type checking, so in actual code field is still assigned to a string value
      name = field as string
      name = <string>field
      
      // Or by type determination
      if (typeof field === 'string') {
        name = field
      }
      Copy the code
  • void

    • function fn () :viod {
        return;
      }
      Copy the code
  • never

    • // This function will never return a result, even if it is empty
      function fn () :never {
        throw new Error('Wrong! ')}Copy the code
  • object

    • let obj: object
      
      obj = {}
      obj = function () {}
      The object type does not restrict whether a variable is an object, but rather limits the specific attribute type of the object
      // Attribute name followed by "?" Represents an optional property
      let _obj: {name: string, age? :number}
      _obj = {name: 'yzy'}
      // If you only need to set the type of a property name, you can say:
      // Note that the propName can be written to any value, no requirement, just format placeholder
      let _obj_: {name: string, [propName: string] :any}
      _obj_ = {name: 'jerry'.age: 18.gender: 'male'}
                 
      // Similarly, when setting a function
      let fn: (a: number, b: number) = > number
      fn = function (num1, num2) :number {
        return num1 + num2
      }
      
      Copy the code
  • Array

    • // String [] represents an array of strings
      let arr: string[]
      arr = ['yzy'.'jerry'.'tom']
      
      // Syntax: type +[]
      // Array< type >
      Copy the code
  • tuple

    • // tuples are arrays of fixed length
      let arr: [string.string]
      arr = ['yzy'.'jerry']
      
      Copy the code
  • enum

    • // The advantage of being enumerable is that you can see at a glance what 0 and 1 mean when writing
      enum Gender {
        male = 0,
        famale = 1
      }
      
      let obj = {name: string.gender: Gender}
      obj = {
        name: 'yzy'.gender: Gender.male
      }
      Copy the code
  • Alias of a type

    • // Easy to reuse
      type genderType =  'male' | 'famale'
      let gender: genderType
      gender = 'male'
      Copy the code
  • Types of assertions

    • In some cases, the type of the variable is clear to us, but not to the TS compiler. In this case, we can tell the compiler the type of the variable using a type assertion, which can take two forms:

      • The first kind of

        • let someValue: unknown = "this is a string";
          let strLength: number = (someValue as string).length;
          Copy the code
      • The second,

        • let someValue: unknown = "this is a string";
          let strLength: number = (<string>someValue).length;
          Copy the code

Compiler options


  • Auto-compile file

    • When compiling a file, using the -w command, the TS compiler automatically monitors the file for changes and recompiles the file if it changes

    • Example:

      • tsc xxx.ts -w
        Copy the code
  • Automatically compile the entire project

    • If you use the TSC directive directly, you can automatically compile all ts files under the current project into JS files

    • However, to be able to use the TSC directive directly, you must first create a TS configuration file tsconfing.json in the root directory of the project

    • Tsconfing.json is a JSON file. After adding the configuration file, you only need TSC instructions to complete the compilation of the entire project

    • Configuration options:

      • include

        • Defines the directory where you want the files to be compiled

        • Default value: [“**/*”]

        • The sample

          • "include": ["src/**/*"."test/**/*"]
            Copy the code
          • In the example, all files in the SRC and test directories are compiled

      • exclude

        • Define the directories that need to be excluded

        • Default: [“node_modules”, “boWER_components “,” jSPM_packages “] default: [“node_modules”, “bower_components”, “jSPM_packages “]

        • The sample

          • "exclude": ["src/hello/**/*"]
            Copy the code
          • In the example, none of the files in the Hello directory are compiled

      • extends

        • Define inherited configuration files

        • The sample

          • "extends": "./configs/base"
            Copy the code
          • In this example, the current configuration file automatically contains all the configuration information in base.json in the configs directory

      • files

        • Specifies a list of files to compile, used only when there are fewer files to compile (same as include)

        • The sample

          • "files": [
              "core.ts"."sys.ts"."types.ts"."scanner.ts"."parser.ts"."utilities.ts"."binder.ts"."checker.ts"."tsc.ts",]Copy the code
          • The files in the list are compiled by the TS compiler

      • complierOptions

        • Compile options are important and complex configuration options in configuration files

        • There are several suboptions in complierOptions to complete the configuration of the compile

          • Project options

            • target

              • Sets the target version for ts code compilation

              • Optional value:

                • ES3 (default), ES5, ES6/ES2015, ES7/ES2016, ES2017, ES2018, ES2019, ES2020, ESNext
              • Example:

                • "complierOptions": {
                    "target": "ES6"
                  }
                  Copy the code
                • In the example, the TS code we wrote is compiled into the ES6 version of JS code

            • lib

              • Specifies the library that the code will contain at runtime, optionally if the project is a browser project

              • Optional value:

                • Es5, ES6, ES2015, ES7, ES2016, ES2017, ES2018, ES2019, ES2020, ESNext, DOM, WebWorker, etc. The default value is the configuration that is guaranteed to run in the browser, and can be set as required in the Node environment.
              • Example:

                • "lib": ["es6"."dom"]
                  Copy the code
                • In this example, the operating environment is ES6 + DOM

            • module

              • Indicates which modular way to compile

              • Optional value:

                • None, CommonJS, AMD, System, UMD, ES6, ES2015, ES2020, ESNext
              • Example:

                • "module": "es6"
                  Copy the code
                • In this example, it is compiled in ES6 modular mode, that is, the compiled JS file follows ES6 modular mode

            • outDir

              • Used to specify the directory where the compiled file resides

              • Example:

                • "outDir": "./src/dist"
                  Copy the code
                • In the example, the target file is compiled to the SRC /dist directory

            • outFile

              • Combine the code into a file

              • Example:

                • "outFile": "./src/dist/app.js"
                  Copy the code
                • In the example, the ts file in include is compiled into the app.js file in the SRC /dist directory

            • allowJs

              • Whether to compile the js file

              • Default value: false

              • Example:

                • "allowJs": true
                  Copy the code
                • In the example, the JS files in the include will also be compiled

            • checkJs

              • Check whether the JS code is syntactic

              • Default value: false

              • Example:

                • "checkJs": true
                  Copy the code
                • In the example, the compiled code is also checked for the type of the variable

            • removeComments

              • Whether to remove comments from compiled files

              • Default value: false

              • Example:

                • "removeComments": false
                  Copy the code
                • In the example, comments are removed from the compiled file

            • rootDir

              • Specify the root directory for your code. By default, the compiled file’s directory structure takes the longest public directory as the root directory. You can specify the root directory manually using rootDir
            • sourceMap

              • Whether sourceMap is generated
              • Default value: false
            • noEmit

              • No compiled file is generated. Note: The compilation process is performed, but no compiled file is generated
              • Default value: false
            • noEmitOnError

              • If the compiled file has errors, the compiled file with errors is not generated
              • Default value: false
            • Strict mode

              • alwaysStrict

                • Used to set whether a compiled file is in strict mode
                • Default value: false
                • When es6 modularity is used in code, there is no need to set strict mode, because once ES6 modularity is used, JS automatically implements strict mode
              • noImplicitAny

                • Whether an implicit any type is allowed

                • Default: false (to allow implicit)

                • Example:

                  • "noImplicitAny": true
                    Copy the code
                  • // If we do not set a type for parameters A and b, their default type is implicit any
                    // If we set "noImplicitAny": true in the configuration, we must manually add types to A and B
                    function fn (a, b) {
                      return a + b
                    }
                    Copy the code
                  • In the example, the implicit any type is not allowed, so we must manually add types to A and B to ensure that the file does not report errors

              • noImplicitThis

                • Whether untyped this is allowed
                • Default: false (to allow)
              • strictNullChecks

                • Whether to strictly check for null values

                • Default: false (not checked)

                • Example:

                  • "strictNullChecks": true
                    Copy the code
                  • // Since the DOM can be empty, the && operator is required to ensure that the DOM exists before executing down
                    let dom = document.getElementById('y')
                    dom && dom.addEventListener('click'.function () {... })Copy the code
                  • In the example, the variable is checked for the possibility of null. Solution: Make a not-empty call

              • strictBindCallApply

                • Strictly check the parameter lists for bind, call, and apply
              • strictFunctionTypes

                • Strictly check the type of the function
              • strictPropertyInitialization

                • Strictly check that the property is initialized
              • strict

                • The master switch of strict mode, that is, alwaysStrict, noImplicitAny, noImplicitThis, strictNullChecks. If set to true, all others are true. When set to false, all else is false; If the master switch and the preceding 7 attributes are set at the same time, the values of the 7 attributes are subject to their own Settings.
            • Additional inspection

              • noFallthroughCasesInSwitch
                • Check that the switch statement contains the correct break
              • noImplicitReturns
                • Check that the function has no implicit return value
              • noUnusedLocals
                • Check for unused local variables
              • noUnusedParameters
                • Check for unused parameters
    • More configuration and explanation

      • {
          "compilerOptions": {
        
            /* Basic options */
            "target": "es5".// Specify the ECMAScript target version: 'ES3' (default), 'ES5', 'ES6'/'ES2015', 'ES2016', 'ES2017', or 'ESNEXT'
            "module": "commonjs".// Specify the module to use: 'commonJS ',' AMD ', 'system', 'umd' or 'es2015'
            "lib": [].// Specify the library file to be included in the build
            "allowJs": true.// Allows javascript files to be compiled
            "checkJs": true.// Report errors in javascript files
            "jsx": "preserve".// Specify JSX code generation: 'preserve', 'react-native', or 'react'
            "declaration": true.// Generate the corresponding '.d.ts' file
            "sourceMap": true.// Generate the corresponding '.map' file
            "outFile": ". /".// Merge the output files into a single file
            "outDir": ". /".// Specify the output directory
            "rootDir": ". /".// To control the output directory structure --outDir.
            "removeComments": true.// Delete all comments after compilation
            "noEmit": true.// No output file is generated
            "importHelpers": true.// Import helper functions from tslib
            "isolatedModules": true.// Treat each file as a separate module (similar to 'ts.transpilemodule').
        
            /* Strict type checking options */
            "strict": true.// Enable all strict type checking options
            "noImplicitAny": true.// There is an error with an implied any type on expressions and declarations
            "strictNullChecks": true.// Enable strict null checking
            "noImplicitThis": true.// An error is generated when this is of type any
            "alwaysStrict": true.// Check each module in strict mode and add 'use strict' to each file
        
            /* Additional checks */
            "noUnusedLocals": true.// An error is thrown when there are unused variables
            "noUnusedParameters": true.// An error is thrown if there are unused arguments
            "noImplicitReturns": true.// An error is thrown when not all code in a function returns a value
            "noFallthroughCasesInSwitch": true.// Switch statement fallthrough error reported. (that is, switch case statements are not allowed to run through)
        
            /* Module parsing options */
            "moduleResolution": "node".// Select a module parsing strategy: 'node' (node.js) or 'classic' (TypeScript pre-1.6)
            "baseUrl": ". /".// The base directory for resolving non-relative module names
            "paths": {},                           // List of module names to baseUrl pathmaps
            "rootDirs": [].// A list of root folders whose combined contents represent the structural contents of the project runtime
            "typeRoots": [].// A list of files containing type declarations
            "types": [].// A list of type declaration filenames to include
            "allowSyntheticDefaultImports": true.// Allow default imports from modules that do not have default exports set.
        
            /* Source Map Options */
            "sourceRoot": ". /".// Specify where the debugger should find TypeScript files instead of source files
            "mapRoot": ". /".// Specify where the debugger should find the mapping file instead of the build file
            "inlineSourceMap": true.// Generate a single soucemaps file instead of generating different sourcemaps files
            "inlineSources": true.// Generate the code and sourcemaps in a file, requiring that either the --inlineSourceMap or --sourceMap attributes are set
        
            /* Other options */
            "experimentalDecorators": true.// Enable the decorator
            "emitDecoratorMetadata": true          // Support metadata for decorators}}Copy the code

Webpack packaging TypeScript


Webpack integration

More often than not, we need to use build tools to package code during actual development

TS can also be used with the build tool. The following uses webpack as an example to introduce how to use TS with the build tool

The steps are as follows:

Initialize the project

Go to the root directory of the project and run NPM init -y to create the package.json file

Download the build tool

The command is as follows:

npm i -D webpack webpack-cli webpack-dev-server typescript ts-loader clean-webpack-plugin html-webpack-plugin
Copy the code

A total of 7 packages were installed:

  • Webpack: Build tool Webpack
  • Webpack-cli: Command line tool for Webpack
  • Webpack-dev-server: development server for Webpack
  • Typescript: TS compiler
  • Ts-loader: TS loader used to compile TS files in webpack
  • Html-webpack-plugin: HTML plug-in in webpack, used to automatically create HTML files
  • Clean-webpack-plugin: A clean plug-in in webpack that cleans the directory first with each build

Configuration webpack

Create webpack configuration file webpack.config.js in root directory:

const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const { CleanWebpackPlugin } = require("clean-webpack-plugin");

module.exports = {
   optimization: {minimize: false // Turn off code compression, optional
   },

   entry: "./src/index.ts".devtool: "inline-source-map".devServer: {
     contentBase: './dist'
   },

   output: {
     path: path.resolve(__dirname, "dist"),
     filename: "bundle.js".environment: {
       arrowFunction: false // Close the arrow function for Webpack, optionally}},resolve: {
     extensions: [".ts".".js"]},module: {
     rules: [{test: /\.ts$/,
         use: {
           loader: "ts-loader"     
         },
         exclude: /node_modules/}},plugins: [
     new CleanWebpackPlugin(),
     new HtmlWebpackPlugin({
       title:'TS test']}}),Copy the code

Configure TS compilation options

Tsconfig. json is created in the root directory and can be configured according to your needs

{
  "compilerOptions": {
    "target": "ES2015"."module": "ES2015"."strict": true}}Copy the code

Modify package.json configuration

Modify package.json to add the following configuration

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

Projects using

Create the TS file under SRC and run NPM run build on the command line to compile the code

Or run NPM start to start the development server

Babel

In addition to WebPack, Babel is often used in development to transform code;

To make it compatible with more browsers, follow these steps to introduce Babel into the project;

TS also supports code conversion at compile time, but only simple code conversion is supported;

For ES6 features such as Promise, TS cannot be converted directly, so Babel is used to convert.

Install dependency packages:

npm i -D @babel/core @babel/preset-env babel-loader core-js
Copy the code

A total of 4 packages are installed, which are:

  • Babel /core: The core tool of Babel
  • @babel/preset-env: Preset environment of Babel
  • @babel-loader: loader for Babel in webpack
  • Core-js: Core-js is used to enable older browsers to support the new ES syntax

Modify the webpack.config.js configuration file

.module: {
  rules: [{test: /\.ts$/,
      use: [
        // Loader has an execution sequence that loads from right to left
        {
          loader: "babel-loader".options: {presets: [["@babel/preset-env",
                {
                  // Target supported version
                  "targets": {"chrome": "58"."ie": "11"
                  },
                  // Corejs version, 3 indicates 3.x
                  "corejs":"3".// Load as needed
                  "useBuiltIns": "usage"}]]}}, {loader: "ts-loader"}].exclude: /node_modules/}}]...Copy the code

In this way, files compiled using TS will be processed by Babel again

Makes the code usable in most browsers

You can also specify the browser version to be compatible with on the Targets TAB of the configuration option

The use of the class


ES6 provides a more object-oriented programming syntax called class

Class is essentially a syntactic sugar for function, which makes writing object prototypes cleaner and more like object-oriented programming syntax.

This chapter combines the usage of TS and simply explains the use of classes

Define the class

classThe name of the class{attribute name: typeconstructor(Parameter: Type){
    this. Attribute name = Parameter} Method name (){.... }}Copy the code

Example:

class Person{
  name: string
	age: number

  constructor(name: string, age: number){
    this.name = name
    this.age = age
  }

  sayHello () {
    console.log('Hello, I amThe ${this.name}`); }}Copy the code

Using class:

const someone = new Person('yzy'.20)
someone.sayHello()
Copy the code

The constructor

Use constructor to define a constructor method;

Note: There can only be one constructor method in TS!

Such as:

class C {
  name: string
  age: number

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

It is also possible to define attributes directly in constructors:

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

The above two definitions are exactly the same!

When a subclass inherits a parent class, it must call the parent class’s constructor (if the subclass also defines a constructor)!

Such as:

class A {
  protected num: number
  constructor(num: number) {
    this.num = num
  }
}

class X extends A {
  protected name: string
  constructor(num: number, name: string) {
    super(num)
    this.name = name
  }	
}
Copy the code

An error will be reported if you do not call super in class X!

encapsulation

An object is essentially a container for properties and methods. Its main function is to store properties and methods, which is called encapsulation

By default, the properties of an object can be modified at will. To ensure data security, the permissions of the properties can be set in TS

  • Static attributes:
    • Properties or methods declared static are no longer instance properties, but class properties;
  • Read-only property (readonly) :
    • If you add a readOnly to the property declaration, the property becomes read-only and cannot be modified
  • TS attributes have three modifiers:
    • Public (default), which can be modified in classes, subclasses, and objects
    • Protected, which can be modified in classes and subclasses
    • Private, which can be changed in the class

Example:

Public:

class Person{
  public name: string // Write or write nothing is public
  public age: number

  constructor(name: string, age: number){
    this.name = name // Can be changed in the class
    this.age = age
  }

  sayHello () {
    console.log('Hello, I amThe ${this.name}`); }}class Rapper extends Person{
  constructor(name: string, age: number){
    super(name, age)
    this.name = name // Subclasses can be modified}}const p = new Person('yzy'.18)
p.name = 'jerry'// Can be modified by object
Copy the code

Protected:

class Person{
  protected name: string
  protected age: number

  constructor(name: string, age: number){
    this.name = name // It can be modified
    this.age = age
  }

  sayHello(){
    console.log('Hello, I amThe ${this.name}`); }}class Rapper extends Person{
  constructor(name: string, age: number){
    super(name, age)
    this.name = name // Subclasses can be modified}}const p = new Person('yzy'.18)
p.name = 'jerry'// Cannot be modified
Copy the code

Private:

class Person{
  private name: string
  private age: number

  constructor(name: string, age: number){
    this.name = name // It can be modified
    this.age = age
  }

  sayHello(){
    console.log('Hello, I amThe ${this.name}`); }}class Rapper extends Person{
  constructor(name: string, age: number){
    super(name, age)
    this.name = name // Cannot be modified in subclasses}}const p = new Person('yzy'.18);
p.name = 'jerry'// Cannot be modified
Copy the code

Attribute accessor

For properties that do not want to be arbitrarily modified, you can set them to private

Making it private directly will make it impossible to modify its properties through objects

We can define a set of methods in a class that read and set properties, called accessors for properties

The methods that read properties are called setter methods, and the methods that set properties are called getter methods

Example:

class Person{
  private _name: string

  constructor(name: string){
    this._name = name
  }

  get name() {return this._name
  }

  set name(name: string) {this._name = name
  }

}

const p1 = new Person('yzy')
// The name property is actually read by calling the getter method
console.log(p1.name)
// Actually modify the name property by calling setter methods
p1.name = 'jerry'
Copy the code

Static attributes

Static properties (methods), also known as class properties. You don’t need to create an instance with static attributes; you can use them directly from the class

Static properties (methods) start with static

Example:

class Tools{
  static PI = 3.1415926

  static sum(num1: number, num2: number){
    return num1 + num2
  }
}

console.log(Tools.PI)
console.log(Tools.sum(123.456))
Copy the code

this

In a class, use this to represent the current object

inheritance

Inheritance is another feature of object orientation

Inheritance allows you to introduce properties and methods from other classes into the current class

Example:

class Animal{
  name: string
  age: number

  constructor(name: string, age: number){
    this.name = name
    this.age = age
  }
}

class Dog extends Animal{
	// Without constructor it automatically says constructor and calls super()
  bark(){
    console.log(`The ${this.name}It's barking! `)}}const dog = new Dog('prosperous wealth'.4)
dog.bark()
Copy the code

Inheritance allows you to extend a class without modifying it

rewrite

When inheritance occurs, if a method in a subclass replaces a method of the same name in the parent class, this is called method rewriting

Example:

class Animal{
  name: string
  age: number

  constructor(name: string, age: number){
    this.name = name
    this.age = age
  }

  run(){
    console.log('Run method in parent class! `); }}class Dog extends Animal{

  bark(){
    console.log(`The ${this.name}It's barking! `)}run(){
    console.log(The run method in the subclass overrides the run method in the parent class! `)}}const dog = new Dog('prosperous wealth'.4)
dog.run()
Copy the code

You can use super in a subclass to complete a reference to the parent class

Abstract Classes [TypeScript only]

Abstract classes are classes that are designed to be inherited by other classes. They can only be inherited by other classes and cannot be used to create instances. Simply put, abstract classes are born to be fathers

abstract class Animal{
  abstract run(): void
  bark(){
      console.log('The animal is calling.')}}class Dog extends Animals{
  run(){
      console.log('The dog is running.')}}Copy the code

Methods that start with abstract are called abstract methods. Abstract methods have no body (not a complete method function) and can only be defined in an abstract class. Subclasses that inherit abstract classes must override the abstract method or report an error

Interface


An interface acts like an abstract class, except that all methods and attributes in an interface have no real values. In other words, all methods in an interface are abstract methods

Interfaces are responsible for defining the structure of a class

Interfaces can limit the interface of an object: an object can only match all properties and methods defined in the interface (no more or less).

You can have a class that implements an interface that includes all of the attributes in the interface (more, but not less)

Note: There can be n interfaces with the same name at the same time, and the actual limitation of this interface is the collection of those interfaces with the same name

Example:

interface Person{
  name: string;
  sayHello(): void;
}
interface Person{
  age: string;
  gender: number;
}

/ / equivalent to
interface Person{
  age: string;
  gender: number;
  name: string;
  sayHello(): void;
}
Copy the code

Example (check object type) :

interface Person{
  name: string;
  sayHello():void;
}

function fn(per: Person){
    per.sayHello();
}

fn({name:'yzy'.sayHello() {console.log(` Hello, I amThe ${this.name}`)}})
Copy the code

Example (implementation) :

interface Person{
  name: string;
  sayHello():void;
}

class Student implements Person{
  constructor(public name: string){}sayHello() {
    console.log('Hello, I am.' + this.name); }}Copy the code

Generic


When defining a function or class, it is sometimes impossible to determine the specific type to be used (the types of return values, parameters, and attributes cannot be determined);

This is where generics come into play;

Here’s an example:

function test(arg: any) :any{
  return arg;
}
Copy the code

In the above example, the test function has an indeterminate parameter type, but if it does, its return value and parameter type are the same.

We use any for both the argument and the return value because the type is uncertain, but this is clearly not appropriate:

Using any turns off type checking for TS, and does not indicate that the parameter and return value are of the same type.

Generic function

Create generic functions

function test<T> (arg: T) :T{
    return arg;
}
Copy the code

Here

is generic;

T is the name we give the type (it doesn’t have to be called T). After we set the generic type, we can use T to represent the type in functions.

So generics are pretty straightforward, they just mean a type;

So how do you use this function?

Use generic functions

Method 1 (direct use) :
test(10)
Copy the code

When used, you can pass arguments directly and the type will be inferred automatically by TS, but sometimes the compiler cannot infer automatically

Method 2 (Specify type) :
test<number> (10)
Copy the code

You can also specify generics manually after a function;

Function to declare more than one generic type

Multiple generics can be specified at the same time, separated by commas:

function test<T.K> (a: T, b: K) :K{
  return b;
}

test<number.string> (10."hello");
Copy the code

When you use generics, you can use them as if they were a normal class.

A generic class

Classes can also use generics:

class MyClass<T>{
  prop: T;

  constructor(prop: T){
      this.prop = prop; }}Copy the code

Generic inheritance

In addition, you can restrict the scope of generics

interface MyInter{
  name: string;
  length: number;
}

type MyType = {
  name: string;
  length: number;
}

abstract class Myclass{
  abstract length: number
}


       
       
         has the same effect as the following code
       
      
function test<T extends MyInter> (arg: T) :number{
  return arg.length;
}
Copy the code

T extends MyInter. T must be a subclass of MyInter. It does not have to use an interface class.

At the end

First of all, thank you for sticking to this, I sincerely hope that this article can help you.