On javascript -- a taste of TypeScript

1, Overview

  • Concept: TypeScript is a superset of JavaScript and supports ES6, Microsoft and open source programming languages
  • characteristic:
    • Debugging and maintenance: there are input prompts, syntax and logic error warnings
    • Type restriction: compilation error
    • Write multi version output at one time: it can be compiled into various JS versions (ES3\ES5...)
  • Scope: that is, the compatible version syntax is also legal in TS

2, Data type

2.1 compilation tools

  • Online compiler: Portal
  • vue use
    • Add single file: < script > tag with lang="ts" attribute
    • typescript: when creating a project
  • Uninitialized variables: errors will be reported directly during compilation

2.2 basic data type

2.2.1 string, number, Boolean

  • character string
    // Writing 1 (common): ts type inference
    let name_temp= 'duke';
    // Writing method 2: with type comments, single and double quotation marks are OK
    let name: string = "duke";
    
    // Template string: the backquote is above the tab key
    let sentence: string = `my name is ${ name + '.' }`;
    
    // Output: duke
    console.log(name);
    // Output: my name is duke
    console.log(sentence);
    
  • number
    // Writing 1 (common): ts type inference
    let num_temp = 3.14;
    // Writing method 2: with type annotation
    let num: number = 100;
    
    // Output: 101
    console.log(num+1);
    
  • Boolean value
    // Writing 1 (common): ts type inference
    let bool_temp = false;
    // Writing method 2: with type annotation
    let bool: boolean = true;
    
    // Output: true
    console.log(bool);
    

    ts type inference: by default, ts infers the variable type according to the initialization value. After initialization, the variable type is fixed

  • Real time error reminder (no reminder in pure js runtime)

2.3 composite type

2.3.1 array, tuple and enumeration

  • Array: the storage sub data type is the same
    // Method 1 (commonly used): initialization upon declaration, which can be an empty array [] 
    let arr0: number[] = [0, 1];
    // Method 2: declaration, initialization and separation
    let arr1: number[];
    arr1 = [1];
    
    // Output: (2) [0,1], 2 is the length of the array
    console.log(arr0);
    // Output: 1
    console.log(arr1[0]);
    
    // If it is miscellaneous, it is written as follows. The type of a is object (see Section 2.4)
    let a = [1, "abc"];
    for (let i of a) {
      console.log(i);
      console.log(typeof i);
    }
    
  • Tuple: the stored sub data is not necessarily the same
    let person: [string, number];
    // If the number is wrong, an error will be reported: person = ["duke", 18, 3];
    // Position error: person = [18, "duke"];
    person = ["duke", 18];
    person[0] = "Jack";
    // Output: (2) ['Jack', 18]
    console.log(person);
    // Deconstruction tuple
    let [name, age] = person;
    // Output: 18
    console.log(age);    
    

    Deconstruction: ES6 syntax, applicable to various composite types let [a, B,...]= object

  • enumeration
        enum Color {
          Red,
          Green = 3,
          Blue,
        }
    	// Enumeration assignment
        let sun: Color = Color.Red;
    
        // Output: 0
        console.log(sun);
        // Output: 4
        console.log(Color.Blue);
        // Output: number
        console.log(typeof Color.Blue);
    

2.3.2 object

  • Conventional implementation
    let stu = {
      name: "duke",
      age: 18,
    };
    // Output: object
    console.log(typeof stu);
    
  • Interface implementation
    // Interface keyword: interface, which can also be used to define objects. I is added before the interface
    interface Person {
      name: string;
      age: number;
    };
    // Object Assignment 
    let duke: Person = {
      name: "duke",
      age: 18,
    };
    // Defines an array in which each element is an object
    let Stu: Person[];
    Stu = [duke];
    // Output: {name: 'duke', age: 18}
    console.log(Stu[0]);
    

2.4 other types

  • null type
    • Definition: setting to "null" value can be understood as setting a pointer to null
    • Code example, commonly used in basic type initialization
      // Union type: the symbol "|", either of which can be used
      let x: string | null ;
      x = null;
      // Output: object
      console.log(typeof x);
      // Output: null
      console.log(x);
      
  • undefine type
    • Definition: undefined, that is, the pointer is not set, and the variable type and value are undefined. It is often used on optional parameters of functions
    • Code example
      let x: string | undefined;
      // 
      x = undefined;
      // Output: undefined
      console.log(typeof x);
      // Output: undefined
      console.log(x);
      
  • Void type: if the function has no return statement, the return value type is void
  • Any type: any type, that is, jump out of the type check, and do not use it for no special reason
  • Object type: object type. Because everything in JS is an object, there is no special reason to use it

3, Function

3.1 conventional writing

  • Code example
    // Compared with JS, only type restrictions are added to the parameters,
    // Limit of return value type: void is defined if there is no return value, and type estimation is adopted if there is a return value but it is not specified
    const test0 = (name: String, age: Number): string => {
      return "name is " + name;
    };
    console.log(test0("duke", 18));
    
    // With default parameters: the default parameters must be placed on the right, and the return value type is presumed
    const test1 = (name: String, age: Number = 18) => {
      return "age is " + age;
    };
    test1("duke");
    
    // With optional parameters: optional parameters must be placed on the right
    //				Here, the age type is implicitly defined | number
    const test2 = (name: String, age?: Number) => {
      return "age is " + age;
    };
    test2("duke");		// Output: age is undefined
    
    // With expansion: the expansion is placed to the right
    const test3 = (...name: string[]) => {
      return "second is:" + name[1];
    };
    console.log(test3("duke", "jack", "york"));
    

3.2 expansion character

  • Definition:, In function test3, the expansion character is used to put the three incoming strings into the character array name one by one; ES6 new syntax for expanding all items in an iteratable object
  • Code example
    const a = [2, 3];
    let b: number[] = [];
    // Array a is expanded into two, three and four numbers, not two, three and four
    // b.push(...a);
    b = [1, ...a, 4];
    // Output: (4) [1, 2, 3, 4]
    console.log(b);
    b.push(...a);
    // Output: (6) [1, 2, 3, 4, 2, 3]
    console.log(b);
    

4, Interface

  • Basic Usage
    // Interface definition
    interface IPerson {
      name: string;
      age: number;
    }
    // Interface inheritance
    interface IStudent extends IPerson {
      sayHi: () => string;
    }
    // Interface assignment
    let duke: IStudent = {
      name: "duke",
      age: 18,
      sayHi: (): string => {
        return "Hi there";
      },
    };
    // Output: duke
    console.log(duke.name);
    // Output: Hi there
    console.log(duke.sayHi());
    

Previous article: a preliminary study of javascript (V) -- BOM

Keywords: Javascript Front-end TypeScript

Added by Cypher87 on Sun, 13 Feb 2022 17:17:27 +0200