Learning TS from Zero (1)

Join us to learn how to make a betO # cui CXR

Organize your first day of study — into three main sections and a few key points

  1. What is the TS
  2. The type of TS
  3. Compile/modify default configuration compile
    • TS Default Configuration
    • TS security detection and automatic calculation types
    • Interface and Type

preface

The first step in learning TS is to deal with the environment

// create a directory mkdir learning-ts // enter the projectcdLearn-ts // Initializes a project NPM init -y // Install typescript NPM I -d typescriptCopy the code

1. What is TS

Simply put, TS is a superset of JS, plus type detection on JS

  1. Write an add function in js and ts and its call to create index.js

     ```js
     function add (a, b) {
         return a + b
     }
     add(1)
     ```
    Copy the code

    The result of executing index.js is a NaN, which is obviously not what we need. The add method is incorrectly called without passing in arguments

    That creates a tsindex. ts

    function add (a, b){
        return a + b
    }
    add(1)
    Copy the code

    TS (2554)\()An argument for ‘b’ was not provided. TS (2554)\()An argument for ‘b’ was not provided. And TS provides the automatic mode of ADD jump

    Let’s do another example

     const names = ["Alice"."Bob"."Eve"];
    
     names.forEach(function (s) {
    
     console.log(s.toUppercase());
     // there is no toUppercase() method and js does not directly indicate that s is a string
     });
    Copy the code
  2. What problems in development did TS solve

  • This allows us to avoid a lot of low-level errors in development (ps: a lot of times it takes a lot of time because of low-level errors)
  • Especially in team development, when common methods are used by others, errors can be avoided

Why we should use TS is not the point but the point is we’re learning TS from zero, what we need is how do we write our code in TS

How to compile TS files into JS? tsc xxx.ts => xxx.js

2. How does TS define a type

TypeScript uses that value as its type when creating a variable and assigning it to a specific value. They’re called automatic inference types, so we don’t have to write type code

let message = 'hello world'
Copy the code

What are the types of TS

Let’s start with the basic types

  • string

  • number

  • boolean

  • Array: there are two ways to write it: 1 type[] 2 generic Array

  • tuples

    let num = 1
    let str = 1
    let isOk = true
    let arr = [1.2.3]
    let arr2 = ['Beijing'.'Shanghai'.'Shenzhen']
    let tuple = ['string'.1]
    Copy the code

    A lot of times you don’t have to define the type just like the code above, TS will automatically infer the type and in most cases you don’t have to explicitly learn the rules of inference. If you’re just starting out, try using fewer type annotations than you thought – TS is better than we thought

  • any

    You can use the well-known any when you’re not sure what the output is, and the type is defined as any when TS automatically calculates the type when it can’t

    let user: any = {
        a: 'A'
    }
    
    user.b // is ok
    user.add() // is ok
    Copy the code

    The TS configuration parameter noImplicitAny (true by default) : enables error reporting for expressions and declarations with an implicit “any” type. When noImplicitAny is true, an error is reported for automatically inferred types of any, which I set to false in most cases

  • object

    You can use interface or you can use type

    interface Person {
        name: string
        age: number
    }
    // type Person = {name: string; age: number }
    
    fucntion greet(person: Person) {
        console.log(`name: ${person.name}, age: ${person: person.age}`)}Copy the code
  • Enumeration:

    Keyword enum reserved for details

    enum {
        Age,
        Name
    }
    Copy the code
  • The rest of the

    Void means there is no type

    Null – this is js null

    Undefined — undefined

  • The joint type

    type Uuid = string | number
    Copy the code

Interface is different from type

  • First of all, both can define objects and functions, and type can define any other type with the =

    interface Obj {
        prop: string
    }
    
    interface greet {
        (arg1: number) :void
    }
    
    type Obj = {
        prop: string
    }
    
    type greet = (arg1: number) :void
    Copy the code
  • Interface and type are not the same for operations like type merge or inheritance

        interface Name { 
          name: string; 
        }
        interface User extends Name { 
          age: number; 
        }
        
        type NameType {
            name: string
        }
    
        type User = NameType & {
            age: number
        }
        
        // Type can also &interface defined interface
        type User = Name & {
            age: number
        }
    Copy the code
  • Interface can extend the interface and type can only be defined with ampersand as above

    // If we add a new variable to the global: wx (applet and JSSDK), we can do window.wx ts without an error
    // type does not extend the Window attribute
    interface Window {
        wx: any
    }
    / / mention another Vue3 CustomComponentProps, ComponentCustomProperties is through the interface can expand the newly added the type of the property
    Copy the code
  • Type can define a type through tpyeof, such as the type of the component you write in Vue. Type CompoenntType = tpyeof CustomComponent

     type CustomComponentRefType = typeof CustomComponent
     // CustomComponent is a self-written component
    Copy the code
  • Type has a lot to do with union types and generics — learn more about that later

Some configuration

  • TSC –init –locale zh-cn will generate a default tsconfig.json annotated in Chinese This makes it easy to know what each tsconfig field configuration represents

  • TSC will default to tsconfig.json in the root directory of the project, of course the command line parameters will take precedence

  • NoEmitOnError: whether to compile the output file if there is an error. Target: compile the version of the output js file es5 es2015, etc. Js version library used in our project: ES function library introduced during compilation, including es5, ES6, ES7, DOM, etc. [“dom”, “es5”, “scripthost”] if target = ES6: [“dom”, “es5”, “scripthost”] if target = es6: [“dom”, “es6”, “dom. Iterable “, “scripthost”] you can manually add libraries, promise, etc

    conclusion

    Document environment => TSC compilation => Add some variation of the configuration of TSC => type type automatic derivation => each document example to go over => type => Interface extensible type can not etc

    Post a link in typescript

    Key points: Study

end

Finally, join us in our studyCopy the code