Author: Yu Wentao

First read: TypeScript Chinese

directory

  • The React project integrates TS
    • Overview of integration processes
    • Install dependencies
    • Why not use ts-Loader
    • Bebel. Config. Json
    • Webpack modify
    • . Eslintrc modify
    • Package. The json configuration
    • Declare the role of the file
  • How should TS be written in the project?
    • Where does it apply?
    • How do you apply it? (Attached todoList project source code)

The React project integrates TS

Overview of integration processes

Install dependencies

@babel/preset-typescript is Babel escape TS

@types/react @types/react-dom is the type library that React depends on

@types/webpack-env is webpack’s global property type library

yarn add typescript @babel/preset-typescript @types/react @types/react-dom @types/webpack-env -D 
Copy the code

Why not use ts-Loader

  • Managing just one compiler is easier
  • Babel is faster. Why is it better to compile typescript with Babel
  • Babel adds polyfills to lower version compatibility processing, while Tsloader does not

There are disadvantages, of course, but the disadvantages can be avoided, and the total benefits are large so we use Babel

  • Type checking cannot be done in real time. The error is an IDE error. This optimization method is to perform type checking every time the development is completedtsc -noEmit

Bebel. Config. Json

{
  "presets": ["@babel/env"."@babel/preset-react"."@babel/preset-typescript"]./ / new
  "plugins": ["react-hot-loader/babel"]}Copy the code

Webpack modify

All React files were renamed to the TSX format because of the stronger TSX semantics

module.exports = (env, args) = > {
/ / PRD mode
  const cssTypePrd = args.env.css === 'prd'

  return {
    entry: './app.tsx'.// Import file
    module: {
        rules: [ // Configure the loader
        {
          test: /\.(jsx|tsx|js|ts)? $/.// Handle es6 syntax and JSX syntax
          loader: 'babel-loader'.include: [
            path.resolve(__dirname, 'src'), // Use the directory
            path.resolve(__dirname, 'app.tsx'), // Use the file],},]},resolve: { // add two suffixes TSX and ts
      extensions: ['.tsx'.'.ts'.'.json'.'.js'].// Try to parse these suffixes in order. If there are multiple files with the same name but different suffixes, WebPack will parse the files with the suffixes listed at the top of the array and skip the rest.}}},Copy the code

. Eslintrc modify

{
    "extends": [
        "eslint-config-ali"."eslint-config-ali/react"."eslint-config-ali/typescript".// Modify the item
        "eslint-config-ali/typescript/react" // Modify the item]."rules": {
        "semi": [2."never"]."no-console": "off"."react/no-array-index-key": "off"."react/prop-types":"off"
    },
    "globals": { // Modify the item
        "GLOBAL_ENV": true
    },
    "ignorePatterns": [ // Ignore folder
        "dist"."node_modules"."*.d.ts"]}Copy the code

Ts – config. Json file

Although the TS-Loader is not required for translation, the TS-Config configuration is required to work with the IDE

{
    "compilerOptions": { // Compile the configuration
        "jsx": "react"."types": ["node"."react"."react-dom"."webpack-env"].// Get the ts dependency of @types on node_modules
        "allowSyntheticDefaultImports": true.// Allow default imports from modules that do not have default exports set. This does not affect the output of the code, just for type checking
        "noEmit": true.// Do no file generation, only type checking}},/ / reference links to https://segmentfault.com/a/1190000021421461
// https://juejin.cn/post/6844904052094926855#heading-17
// There is no TS-loader here, so tsconfig only serves to prompt the IDE
Copy the code

Package. The json configuration

    "typeCheck": "tsc --noEmit" // Add ts type check command does not produce output file
Copy the code

Declare the role of the file

Once you’ve done this, you’ll notice that the import of less and img files is marked in red, because these files require type declarations and global variables

Create a new externals.d.ts

declare module '*.less' { / / less error

    const classes: { [className: string] :string };
  
    export default classes;
  
   }

// File error declaration
declare module '*.svg'

declare module '*.png'

declare module '*.jpg'

declare module '*.jpeg'

declare module '*.gif'

declare module '*.bmp'

declare module '*.tiff'

// Global variables
declare var GLOBAL_ENV: string;


Copy the code

How should TS be written in the project?

TS is designed for more secure and efficient type hints and checking

Where does it apply?

What are the basics?

Function type interfaces and type aliases

  • The difference between

    • See this article [What’s the difference between interface and Type in typescript?] (github.com/SunshowerC/…).
    The name of the The difference between The same
    interface No union types or tuples Both can describe objects and functions, and both allow extension
    type Unable to declare merge Both can describe objects and functions, and both allow extension

The generic

  • The function of generic

    function test<T> (name:T) = >{
    	console.log(name)
    }
    
    test<string> ('Ming')
    Copy the code
  • A class of generic

    class Test<T>{
        constructor(params:T) {
            console.log(params)
        }
    }
    
    new Test<Number> (1)
    Copy the code
  • Interface generic

    interface Test<T> {
    	name: string.age: number.info: T
    }
    
    const test:Test<string> = {
        name: 'millet'.age:11.info: 'I'm a student'
    }
    Copy the code

The enumeration

  • Maintain a constant

    • Suggest writing
    enum Test {
        NAME = 'name',
        AGE = 'age',}Copy the code

Typeof and keyof usage

  • typeof

    • For enumerations and values that define types

      const a: number = 3
      
      // const b: number = 4
      const b: typeof a = 4
      Copy the code
  • keyof

    • Only for types

      interface Point {
          x: number;
          y: number;
      }
      
      // type keys = "x" | "y"
      type keys = keyof Point;
      Copy the code

How do you apply it?

Write a simple todoList

The project address

  • Function component definition
  • Functions component props definition
  • The definition of hooks
  • Definition of your own method

Pay attention to the pit?

  • The class component defaultprops cannot be associated with the types of props, but the function component can, see the link.
  • ReactNode. Other ReactNodeArray and ReactChild are not fault-tolerant
  • Function component if usedReact.FCType cannot return the arr.map structure directly because arr.map may return as[]

Further reading

Built-in functions for TS

The TS lib declaration file has some built-in utility functions to use

  • Partial

    // Make all attributes of object attributes optional
    interface User {
        name: string.age: number
    }
    
    /*
    * {
     name?: string,
     age?:string
    }
    */
    type Test = Partial<User>
    
    Copy the code
  • Required

    // Convert all attributes to required attributes
    interfaceUser { name? :string, age? :number
    }
    
    /* * { name: string, age:string } */
    type Test = Required<User>
    Copy the code
  • Readonly

    // All properties become read-only
    interface User {
        name: string.age: number
    }
    
    /* * { readonly name: string, readonly age:string } */
    type Test = Readonly<User>
    Copy the code
  • Pick

    // Get an attribute of all object types
    interface User {
        name: string,
        age: number
    }
    
    /* * { name: string, } */
    type Test = Pick<User, 'name'>
    Copy the code
  • Record

    // Assign a new object type to the object type
    interface User {
        name: string.age: number
    }
    
    /* * { test: User, } */
    type Test = Record<'test', User>
    Copy the code
  • Omit

    // The object type excludes an attribute
    // Assign a new object type to the object type
    interface User {
        name: string.age: number
    }
    
    /* * { name: string, } */
    type Test = Omit<User, 'age'>
    Copy the code

The TS?and!Operator usage

Question marks in TypeScript? With exclamation marks! What does that mean?

Refer to the link

  • Question marks in TypeScript? With exclamation marks! What does that mean?
  • React + TypeScript processing for default Props
  • Why compiling typescript with Babel is a better choice
  • What’s the difference between interface and Type in typescript?