current position:Home>[25] typescript

[25] typescript

2021-08-29 04:53:19 woow_ wu7

Navigation

[react] Hooks

[ encapsulation 01- Design patterns ] Design principles and Factory mode ( Simple abstract method ) Adapter pattern Decorator mode
[ encapsulation 02- Design patterns ] Command mode The flyweight pattern Portfolio model The proxy pattern

[React Practice from scratch 01- backstage ] The code segment
[React Practice from scratch 02- backstage ] Access control
[React Practice from scratch 03- backstage ] Customize hooks
[React Practice from scratch 04- backstage ] docker-compose Deploy react+egg+nginx+mysql
[React Practice from scratch 05- backstage ] Gitlab-CI Use Docker Automated Deployment

[ Source code -webpack01- Pre knowledge ] AST Abstract syntax tree
[ Source code -webpack02- Pre knowledge ] Tapable
[ Source code -webpack03] Handwriting webpack - compiler Simple compilation process
[ Source code ] Redux React-Redux01
[ Source code ] axios
[ Source code ] vuex
[ Source code -vue01] data Response type and Initialize rendering
[ Source code -vue02] computed Response type - initialization , visit , The update process
[ Source code -vue03] watch Listening properties - Initialization and update
[ Source code -vue04] Vue.set and vm.$set
[ Source code -vue05] Vue.extend

[ Source code -vue06] Vue.nextTick and vm.$nextTick

[ Source code -react01] ReactDOM.render01
[ Source code -react02] Handwriting hook Dispatch -useState Realization

[ Deploy 01] Nginx
[ Deploy 02] Docker Deploy vue project
[ Deploy 03] gitlab-CI

[ Data structures and algorithms 01] Binary search and sort

[ thorough 01] Execution context
[ thorough 02] Prototype chain
[ thorough 03] Inherit
[ thorough 04] The event loop
[ thorough 05] currying Partial function Function memory
[ thorough 06] Implicit conversion and Operator
[ thorough 07] Browser caching mechanism (http Caching mechanisms )
[ thorough 08] Front end security
[ thorough 09] Depth copy
[ thorough 10] Debounce Throttle
[ thorough 11] Front-end routing
[ thorough 12] Front-end modularization
[ thorough 13] Observer mode Publish subscribe mode Two way data binding
[ thorough 14] canvas
[ thorough 15] webSocket
[ thorough 16] webpack
[ thorough 17] http and https
[ thorough 18] CSS-interview
[ thorough 19] Handwriting Promise
[ thorough 20] Handwritten functions
[ thorough 21] Data structures and algorithms - Binary search and sort
[ thorough 22] js and v8 Garbage collection mechanism
[ thorough 23] JS Design patterns - agent , Strategy , Single case
[ thorough 24] Fiber
[ thorough 25] Typescript

[ Front end learning java01-SpringBoot actual combat ] Environment configuration and HelloWorld service
[ Front end learning java02-SpringBoot actual combat ] mybatis + mysql Add, delete, modify and search songs
[ Front end learning java03-SpringBoot actual combat ] lombok, journal , Deploy
[ Front end learning java04-SpringBoot actual combat ] Static resources + Interceptor + Front and back end file upload
[ Front end learning java05-SpringBoot actual combat ] Commonly used annotations + redis Realize the statistical function
[ Front end learning java06-SpringBoot actual combat ] Inject + Swagger2 3.0 + unit testing JUnit5
[ Front end learning java07-SpringBoot actual combat ] IOC Scanner + Business + Jackson
[ Front end learning java08-SpringBoot Practical summary 1-7] A staged summary
[ Front end learning java09-SpringBoot actual combat ] Multi module configuration + Mybatis-plus + Single multi module packaging deployment
[ Front end learning java10-SpringBoot actual combat ] bean Assignment conversion + Parameter checking + Global exception handling
[ Front end learning java11-SpringSecurity] To configure + Memory + database = Three ways to achieve RBAC
[ Front end learning java12-SpringSecurity] JWT
[ Front end learning java13-SpringCloud] Eureka + RestTemplate + Zuul + Ribbon

( One ) Pre knowledge

(1) Some words

vite  Hurry up 
declare  Statement 
interop  Interoperation  // esModuleInterop=true  Express commonjs Modules can be used import and require Two kinds of grammar 

primavera  The youth team   spring 
survey  research   survey   measurement 
preserve  Retain   Protect 
 Copy code 

(2) How to install typescript

  • cnpm install typescript -g

(3) tsc command

  • tsc Order official documents
  • When installed typescript after , You can use tsc The command
  • Commands are divided into many categories , such as compilerOptoin, buildOption, watchOption
tsc index.ts //  Compiled by tsconfig.json Defined in the project index.ts file 
tsc src/*.ts //  Compile all scr Medium ts file 
tsc --project tsconfig2.json //  Specify specific tsconfig.json File to compile 

compilerOption
tsc --init //  initialization typescript project , And generate a tsconfig.json file 
tsc --all //  Displays all compiler command options 
tsc --version //  Print compiler version information 
 Copy code 

(4) keyof Index type query ,T[K] Index access

  • keyof
    • Index type query - The operator
    • For any ( type T ),( keyof T ) return T Known public ( Property name ) Of ( Joint type )
  • T[K]
    • Index access - The operator
    • Returns the corresponding in the interface keyof T The type corresponding to the index

(5) typeof Type protection ,instanceof Type protection

  • typeof
    • Type protection
    • Pay attention to is typeof v=name Medium name Must be number string boolean symbol
  • instanceof
    • Type protection
    • instanceof Type protection is through ( Constructors ) A way to refine types
    • instanceof The right side requires a constructor ,ts It will be refined to
      • 1. Of this constructor prototype Type of attribute , If its type is not any
      • 2. Construct a union of the types returned by the signature

(6) Type predicate is

  • 1. What is? ( Type protection ) ?
    • To define a type of protection , We just need to define a function ,( The return value of this function ) It's a ( Type predicate is )
  • 2. Syntax of type predicates
    • parameterName is Type
    • parameterName Must be a parameter name from the current function signature - That is, it must be an argument to the function
    1. some is Points for attention

(7) readonly and const The difference between

  • Neither can be modified
  • Variable usage const, The properties of an object are defined by readonly

(8) ( Type the alias type ) and ( Interface interface ) The difference between

  • type
    • type The type alias will give ( Type a new name )
    • type It can act on the original value , Joint type , Tuples , And any other type that requires handwriting , and instance For objects
    • type Will not create a new type , It creates a new name to refer to that type
    • type It can also be generic
  • type and interface The difference between
    • interface Is to create a new type , and type No new type , Just give the type a new name
    • type It can act on the original value , Joint type , Tuples and other types that need handwriting , and interface For objects
    • type Can not be extends Inherit and implements Realization

(9) enumeration

  • Enumeration classification :
    • ( Enumeration of numbers ), ( String Enum ), ( Heterogeneous enumeration - Mix numbers and strings ), ( const Constant enumeration )
    • ( External enumeration )
  • Reverse mapping
    • Numeric enumeration members also have - ( Reverse mapping )
    • In fact, string enumeration can also , however key and value To be the same
enum Good {
  name = 1,
  age = 3
}
const number = Good.name // 1
const string = Good[number] // 'name'

 analysis :
1.  Numeric enumeration members can  -  Reverse mapping 
2. 
 problem : Why can numeric enumeration members be inversely mapped ?
 answer : because  - enum enumeration , It can be used as data , It can also be used as a type 
 Expand :enum  and  class  You can do both types , You can also do data 
3.
Good[name]  yes  ( T[K] -  Index access operator  ), therefore  ( name Must be a type , namely K Must be a type  )
 Copy code 

(10) jsx

  • The website links
  • Value type : enumeration
  • Range of values :'preserve' 'react-native' 'react'
  • meaning : Appoint jsx Code generation , These patterns only work during the code generation phase
    • 1 preserve => The generated code will retain jsx Subsequent conversion operations ( For example, you can use babel), The output file has .jsx
    • 2 react => Generate React.createElement, There is no need to convert before use , Output file with .js
    • 3 react-native => Keep all jsx, The output file extension is .js
  • How to configure : stay tsconfig.json File configuration items compilerOptions Pass through ( jsx Options ) To specify the
  • as
    • jsx Assertions in use as grammar , Instead of using <foo>bar grammar

(11) Generic

  • Generic functions
    • Generics are functions , This function can ( Applicable to multiple types ), So called ( Pantomorphism )
    • Generics and any The difference between : Generics do not lose information
    • ( Generic functions ) How to use
      • 1. Pass in all parameters , Include type parameters
      • 2.( type inference ), Automatically determine according to parameters T type
  • Generic variables :( Generic variables ) It stands for ( Any type )
  • The generic type - Generic interface , Generic interface parameters
    • Type of generic function
      • let myIdentity: <T>(arg: T) => T = identity;
      • let myIdentity: {<T>(arg: T): T} = identity;
    • You can use different ( Generic parameter name )
    • You can create ( Generic interface , Generic classes ), But you can't create ( Generic enumeration , Generic command space )
    • Generic interface - ( The generic parameter ) It can also be used as a whole ( Parameters of generic interface )
  • Generic constraint - to T The constraints of - extends
    • stay ( Generic constraint ) Use in ( Type parameter )
    • The constrained generic variable no longer represents any type
function loggingIdentity<T>(arg: T): T {
    console.log(arg.length);  // Error: T doesn't have .length
    return arg;
}
(1) problem :
  -  above  (  Type variable T )  Represents any type of , So take arg.length Report errors , Because if T yes number, It's not length Attribute 
  
(2) How to solve :
  -  hold  (  Generic variables T )  As  (  type  )  Part of use , such as  ( T[] ), This increases flexibility 
  -  Specific examples are as follows 
  
(3)  terms of settlement 1
function loggingIdentity<T>(arg: T[]): T[] {
    console.log(arg.length);  // Array has a .length, so no more error
    return arg;
}

(4)  terms of settlement 2 -  Generic constraint 
interface Lengthwise {
    length: number;
}
function loggingIdentity<T extends Lengthwise>(arg: T): T { 
    // !!!!!! -------  adopt  extends  To restrain T The specific properties of  ------- !!!!!!
    // !!!!!! -------  adopt  extends  To restrain T The specific properties of  ------- !!!!!!
    // !!!!!! -------  adopt  extends  To restrain T The specific properties of  ------- !!!!!!
    console.log(arg.length); //  After generic constraints ,T It has. length attribute , So you can access 
    return arg;
}
 Copy code 

( Two ) tsconfig.json

(2.1) How to generate tsconfig.json file

  • tsc --init A with the default configuration is generated tsconfig.json file
  • If a directory exists tsconfig.json file , So that means the catalog is typescript project Of root directory
  • tsconfig.json The file specifies the... Used to compile the project ( Root file ) and ( Compilation options )

(2.1) tsconfig.json Configuration item

compilerOptions

  target 
  // target 
  //  meaning : take ts What version of js file  
  //  Optional value :"ES3", "ES5", "ES6"/ "ES2015", "ES2016", "ES2017","ESNext"
  //  The default value is :"ES3"
  // "ESNext"  Express tc39 Abreast of the times ES proposed features
  
  module
  // module
  //  meaning : take ts Translate it into js When you file ,js What does the file use ( Module system )
  //  Optional value :"None", "CommonJS", "AMD", "System", "UMD", "ES6", "ES2015","ESNext"
  //  Default value according to  --target perhaps target  The options are different and not 
  // - target=es6 when ,module=es6
  // - target No es6 when ,module=commonjs
  // -  such as :
  // - module=es6 when , After packaging js In file , Use import
  // - module=commonjs when , After packaging js In file , Use require
  
  allowJs
  // allowJs
  //  Value type :boolean , The default value is false
  //  meaning : Whether compilation is allowed javascript file ,true said js Suffix files will also be typescrpt Editor compilation 
  //  Example 
  // allowJs=true, you are here ts The file introduces a js The document ( No mistake. )
  // allowJs=flase, you are here ts The file introduces a js Document meeting ( Report errors )
  
  baseUrl
  // baseUrl
  //  meaning : For parsing ( Non relative module name ) Of ( Base directory ), It can also be regarded as specifying ( root directory )
  //  coordination :baseUrl + paths  It can achieve something similar alias The function of 
  
  paths
  // paths
  //  Value type :Object
  //  meaning :(  Module name  )  or  (  Path mapping  )  A list of , Be similar to alias
  //  characteristic : Need to match  ( baseUrl )
  //  Example 1
  // "baseUrl": "./",
  // "paths": { "@/*": ["src/*"] } 
  //  Example 2
  // "baseUrl": "./",
  //   "paths": {
  //      "*": ["types/*"]
  //   },
  //  "esModuleInterop": true, 
  //  Example 2 Express : Finding the declaration file requires   Current directory /types Look for 
  
  
  esModuleInterop
  // esModuleInterop
  //  meaning :`esModuleInterop` The function of the option is to support the use of `import d from 'cjs'` Way to introduce `commonjs` package 
  //  explain : Originally  commmonjs Only support require Methods ,esModuleInterop=true, You can use import The way 
  // interop It means to operate with each other 
  
  
  typeRoots
  types
  // typeRoots  and  types
  //  Value type : Both are array
  // - typeRoots The members of the array are (@types The folder path of the package )
  // - types The members of the array are (npm Package name )
  //  scene : By default, all visible  @types package   Will be included in the compilation process 
  // - typeRoots scene : If you specify typeRoots, only typeRoots Array ( Designated folder ) Medium (@types The package will be included )
  // - types scene : If you specify types, only types Array (npm The package will be included )
  //  Case study 
  // "typeRoots": ["./typings"], //  Only typings Under folder @types The package will be included ,node_modules The in will not be included 
  //  "types": ["jquery"], // jquery library npm The package will be included 
  //  Website shows 
  // - https://www.tslang.cn/docs/handbook/tsconfig-json.html#types-typeroots-and-types
  
  
  jsx
  // jsx
  //  Value type : enumeration 
  //  Range of values :'preserve' 'react-native' 'react'
  //  meaning : Appoint jsx Code generation , These patterns only work during the code generation phase 
  // 1 preserve =>  The generated code will retain jsx Subsequent conversion operations ( For example, you can use babel), The output file has  .jsx
  // 2 react =>  Generate  React.createElement, There is no need to convert before use , Output file with  .js
  // 3 react-native =>  Keep all jsx, The output file extension is  .js
     Pattern              |  Input         |  Output                          |  Output file extension  |
    | -------------- | --------- | ---------------------------- | ------- |
    | `preserve`     | `<div />` | `<div />`                    | `.jsx`  |
    | `react`        | `<div />` | `React.createElement("div")` | `.js`   |
    | `react-native` | `<div />` | `<div />`                    | `.js`   |

  
  outDir //  Output folder 
  rootDir //  Input folder 


----  Split line  ----
include
exclude
  // include  and  exclude
  //  Value type :Array
  //  meaning 
  // -  When not set include when , The compiler contains... By default ( The current directory and subdirectories ) All of the typescript file (.ts, .d.ts  and  .tsx)
  // -  When (allowJs=true) when , It also includes all js file (.js and .jsx)
  //  Example 
  // "include": ["src/**/*"] //  Represents compilation src/ Two level directory / All in the third level directory ( Three level directory ) Medium typescript file 
 Copy code 
  • Concrete tsconfig.json Configuration instructions
{
  "compilerOptions": {
    /*  The basic options  */
    "target": "es5",                       //  Appoint  ECMAScript  Target version : 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', or 'ESNEXT'("ESNext" Means up to date ES grammar , Including still in stage X Stage )
    "module": "commonjs",                  //  Specify module to use : 'commonjs', 'amd', 'system', 'umd' or 'es2015'
    "lib": [],                             //  Specify the library files to include in the compilation 
    "allowJs": true,                       //  Permitted compilation  javascript  file 
    "checkJs": true,                       //  The report  javascript  Error in file 
    "jsx": "preserve",                     //  Appoint  jsx  Code generation : 'preserve', 'react-native', or 'react'
    "declaration": true,                   //  Generate corresponding  '.d.ts'  file 
    "sourceMap": true,                     //  Generate corresponding  '.map'  file 
    "outFile": "./",                       //  Merge output files into one file 
    "outDir": "./",                        //  Specify output directory 
    "rootDir": "./",                       //  Used to control the output directory structure  --outDir.
    "removeComments": true,                //  Delete all comments after compilation 
    "noEmit": true,                        //  Do not generate output file 
    "importHelpers": true,                 //  from  tslib  Import helper functions 
    "isolatedModules": true,               //  Make each file a separate module  ( And  'ts.transpileModule'  similar ).

    /*  Strict type checking options  */
    "strict": true,                        //  Enable all strict type checking options 
    "noImplicitAny": true,                 //  Implicit in expressions and declarations  any Wrong type 
    "strictNullChecks": true,              //  Enable strict  null  Check 
    "noImplicitThis": true,                //  When  this  Expression value is  any  When it comes to type , Generate an error 
    "alwaysStrict": true,                  //  Check each module in strict mode , And add it to every document  'use strict'

    /*  Additional checks  */
    "noUnusedLocals": true,                //  When there are unused variables , Throw an error 
    "noUnusedParameters": true,            //  When there are unused parameters , Throw an error 
    "noImplicitReturns": true,             //  When not all code in a function has a return value , Throw an error 
    "noFallthroughCasesInSwitch": true,    //  The report  switch  Of the statement  fallthrough  error .( namely , Don't allow  switch  Of  case  Sentence through )

    /*  Module resolution options  */
    "moduleResolution": "node",            //  Select module resolution strategy : 'node' (Node.js) or 'classic' (TypeScript pre-1.6). The default is classic
    "baseUrl": "./",                       //  Base directory for resolving non relative module names 
    "paths": {},                           //  Module name to based on  baseUrl  List of path mappings for 
    "rootDirs": [],                        //  Root folder list , Its combined content represents the structural content of the project at runtime 
    "typeRoots": [],                       //  List of files containing type declarations 
    "types": [],                           //  List of type declaration filenames to include 
    "allowSyntheticDefaultImports": true,  //  Allow default import from modules with no default export set .

    /* Source Map Options */
    "sourceRoot": "./",                    //  Specifies that the debugger should find  TypeScript  Location of files instead of source files 
    "mapRoot": "./",                       //  Specifies where the debugger should find the map file instead of the build file 
    "inlineSourceMap": true,               //  Generate single  soucemaps  file , Rather than  sourcemaps  Generate different files 
    "inlineSources": true,                 //  Linking code to  sourcemaps  Build to a file , Requirements are set at the same time  --inlineSourceMap  or  --sourceMap  attribute 

    /*  The other options  */
    "experimentalDecorators": true,        //  Enable decorator 
    "emitDecoratorMetadata": true,         //  Provide metadata support for decorators 
    "strictFunctionTypes": false           //  Disable bidirectional covariance checking of function parameters .
  },
  /*  Specify the compiled file or exclude the specified compiled file  */
  "include": [
      "src/**/*"
  ],
  "exclude": [
      "node_modules",
      "**/*.spec.ts"
  ],
  "files": [
    "core.ts",
    "sys.ts"
  ],
  //  Inherit configuration from another configuration file 
  "extends": "./config/base",
  //  Give Way IDE When saving the file, according to tsconfig.json Regenerate the file 
  "compileOnSave": true //  Supporting this feature requires Visual Studio 2015, TypeScript1.8.4 Above and install atom-typescript plug-in unit 
}
 Copy code 

( 3、 ... and ) Declaration file ( .d.ts )

(3.1) Statement document summary

  • Classification of Libraries
    • Library divided into ( Global Library ) and ( Modular Library )
  • What is? UMD modular
    • UMD Module means : It can be used as a module , It can also be used as a library for global modules
  • The declaration file can be ( value , Or type )
    • interface type Corresponding to the type
    • let const var function namespace Corresponding value
    • class enum It can be worth , It can also be type

(3.2) How to write a - ( Global declaration file )

  • except interface and type, Other global types need to pass declare To declare
  • namespace It's equivalent to a ( object ),namespace Can be nested
  • If I have two Homonymous interface, will ( Declaration of merger )
1.  Global variables 
declare var foo: number;
declare let foo: number;
declare const foo: number;

2.  Global function 
declare function greet(greeting: string): void;

3.  function overloading 
-  explain :`getWidget` The function receives a number , Return to a component , Or receive a string and return an array of components 
-  Statement :
declare function getWidget(n: number): Widget; 
declare function getWidget(s: string): Widget[];

4.  Interface 
 If there are two people with the same name interface, Will declare merge 
interface GreetingSettings { 
  greeting: string; 
  duration?: number; 
}

5.  Alias 
type GreetingLike = string | (() => string)


6.  Namespace  (  Equivalent to an object  ),(  Notice that this is the object , Not the type of object , The type of object can be interface To declare  )
declare namespace GreetingLib {
  interface LogOptions {
      verbose?: boolean;
  }
  interface AlertOptions {
      modal: boolean;
  }
}


7.  class  (  Declarative classes  -  Both data and type  )
(  It can be either a value or a type , except class class , also enum enumeration  )
declare class Greeter {
  constructor(greeting: string);
  greeting: string;
}
 Copy code 

(3.3) How to write a - ( Module declaration file )

  • 1. The modular library needs to be modified tsconfig.json In the document baseUrl and path as well as ``
{ 
  "compilerOptions": {
     "baseUrl": "./",
     "paths": {
         "*": ["types/*"]
     },
     "esModuleInterop": true, 
     // `esModuleInterop` The function of the option is to support the use of `import d from 'cjs'` Way to introduce `commonjs` package 
  }
}
 Indicates that the declaration file is going to : In the current folder ,types Find... In the folder 
 Copy code 
  • 2. The module declaration is basically the same as the global declaration , It's just that the module is import and export Of , So the use needs import, And the declaration requires export
  • 3. Of course, the types of modules are more than esmodule, Other module types can follow the and rules of the corresponding module

(3.4) Specification of declaration file

Here are only some points that I don't pay much attention to

  • Not in ( In the callback function ) Use ( Optional parameters ), Because in most cases, the parameters of the callback function are determined , Unless there is a real alternative
  • Don't cry because it is ( The number of callback function parameters is different ) And write ( Different overloads )
/*  error  */ 
declare function beforeAll(action: () => void, timeout?: number): void;  
declare function beforeAll(action: (done: DoneFn) => void, timeout?: number): void;

* should * Only use the maximum number of parameters to write an overload :
/* OK */ 
declare function beforeAll(action: (done: DoneFn) => void, timeout?: number): void;
 Copy code 

Information

copyright notice
author[woow_ wu7],Please bring the original link to reprint, thank you.
https://en.qdmana.com/2021/08/20210829045313694p.html

Random recommended