当前位置:网站首页>Typescript for Web Learning

Typescript for Web Learning

2022-06-26 00:47:00 on the moon

One . TypeScript What is it?

  • TypeScript yes JavaScript A superset of type , Expanded JavaScript The grammar of ;
  • TypeScript The design goal is to develop large-scale applications , It can compile pure 、 concise JavaScript Code , Can run in any browser 、 On any computer and any operating system , And it's open source ;
  • TypeScript Provide static type checking at compile time through type annotation , It can advance the debugging from the running period to the coding period , Such as type checking 、 The function of cross-border inspection can really work ;
  • TypeScript The development experience of is far more than that of the past JavaScript Development experience , You don't need to run a program to fix potential bug;
  • TypeScript Support future ES6 even to the extent that ES7. stay TypeScript in , You can use it directly ES6 The latest features of , When compiling, it will automatically compile to ES5.

 Insert picture description here

Two . TypeScript To configure

  1. Install well NodeJS after , Run the terminal as an administrator , Use npm -g install ts-node typescript Command for global installation ;
  2. stay VS Code In the development , install TSLint、TypeScript Hero、Bracket Pair Colorizer Etc ;
  3. Create a new one .ts Postfix file , Write a paragraph at will JS Code , Click Run to see if the configuration is successful .

3、 ... and . Variable declarations

Use let and const A new way of declaration to replace var, And add the type description , And the scope is block level, i.e {} As a boundary .
const It's right let An enhancement of , It can prevent a variable from being assigned again .

for example :

let lang: string = 'TypeScript';// If type description is omitted ,TS Automatic inference is also possible 
lang = 1010;//error!  Union types can be used if necessary :let lang: number | string = 'TS';
let age: number = 89;
let age = 64;//error!

const pi: number = 3.14159;//pi It cannot be changed in the future , Similar constant 
pi = 3.14;//error!

Four . deconstruction

Put the object 、 The elements in the array are split into specified variables , For ease of use

// Deconstruct arrays 
let input = [89, 64, 2018, 10];
let [first, second] = input;// Pay attention to []
console.log(first); // 89
console.log(second); // 64
let [one, ...others] = input; //...other Means to expand the remaining array 
console.log(...others);  //64 2018 10
let newArr = [89, ...others, 18];
console.log(newArr);  // [ 89, 64, 2018, 10, 18 ]

// Deconstruction object 
let o = {
    
  a: "foo",
  b: 12,
  c: "bar"
};
let {
    a, b} = o;// Pay attention to {}, And the variable name must be consistent with the attribute name in the object 
console.log(a, b);  //foo 12

5、 ... and . function

TypeScript by JavaScript Function adds extra functionality , Let's make it easier to use .

1. Use the full function type definition

Variable name : type
function Function name (): return type {}

// Name the function , There are complete parameters and return types . Don't have to ,TS Type inference will be done automatically, but... Is recommended !
function add(x: number, y: number): number {
    
  return x + y;
}
// Anonymous functions 
let myAdd = function(x: number, y: number): number {
     return x + y; };
console.log(myAdd(1, '2'));//error
console.log(myAdd(1));//error
console.log(typeof myAdd(1, 2));//number 

2. Optional parameters

JavaScript in , Each parameter is optional , Can pass but not pass ; When I didn't pass the reference , Its value is undefined.
stay TypeScript Use in Variable name ?: Type implements the function of optional parameters .

for example , We want to make last name It's optional :

function buildName(firstName: string, lastName?: string) {
    
    if (lastName)
        return firstName + " " + lastName;
    else
        return firstName;
}
console.log(buildName("Bob"));  // works correctly now
console.log(buildName("Bob", "Adams", "Sr."));  // error, too many parameters
console.log(buildName("Bob", "Adams"));  // right

Be careful : Optional parameters must be placed after the necessary parameters !!


3. Default parameters

stay TypeScript in , We can also provide a default value for the parameter , When the user does not pass this parameter or the value passed is undefined when , They are called parameters with default initialization values .

Modify the above example , hold last name The default value of is set to "Smith":

function buildName(firstName: string, lastName = "Smith") {
    
    return firstName + " " + lastName;
}
console.log(buildName("Bob"));                  // right, returns "Bob Smith"
console.log(buildName("Bob", undefined));       // right, returns "Bob Smith"
console.log(buildName("Bob", "Adams", "Sr."));  // error, too many parameters
console.log(buildName("Bob", "Adams"));         // right

Parameters with default initialization after all required parameters are optional , Same as optional parameters , When you call a function, you can omit .

Be careful : Unlike the optional parameters , The default parameter does not need to be placed after the required parameter .


4. The remaining parameters

Necessary parameters , Default and optional parameters have one thing in common : They represent a parameter .

Sometimes , You want to manipulate multiple parameters at the same time , Or you don't know how many parameters will be passed in , stay TypeScript in , You can collect all the parameters into one variable .

function greeting(firstName: string, ...restName: string[]) {
    
  return `Hello ${
      firstName} ${
      restName.join(' ')}!`;
}
console.log(greeting('Osama', 'bin', 'Muhammad', 'bin', 'Awad', 'bin', 'Laden'));
console.log(greeting('Laden'));
 // The remaining parameters , Will be treated as an unlimited number of optional parameters . You can have none of them , You can also have any 

5. Arrow function

JavaScript in ,this The value of is specified only when the function is called . This is a powerful and flexible feature , But it takes time to figure out what the context of the function call is , This is not a very simple thing , Especially when returning a function or passing a function as an argument .

To solve this problem , We tie the correct when the function is returned this. The arrow function can save the this value , Instead of the value at call time .

// No parameter , The function body code has only one line , The result of this line is the return value of the function 
let greeting1 = () => `Hello TS!`;
console.log(greeting1());  // Hello TS!

// One parameter , The function body code has only one line , The result of this line is the return value of the function 
let greeting2 = (name: string) => `Hello ${
      name}`;
console.log(greeting2('Kitty'));  // Hello Kitty

// Two or more parameters , The function body code has only one line , The result of this line is the return value of the function 
let add1 = (n1: number, n2: number) => n1 + n2;
console.log(add1(1, 2));   // 3

// Two or more parameters , Function body code is more than one line , You have to use {} The parcel , And explicitly give return
let add2 = (n1: number, n2: number) => {
    
  let sum = n1 + n2;
  return sum;// Change it to sum++ What is the result? ?
}
console.log(add2(1, 2));  // 3

6、 ... and . class Class

TypeScript It's object-oriented JavaScript.
Class describes the common properties and methods of the created object .
TypeScript Support all object-oriented features , such as class 、 Interfaces, etc. .

1. Definition and use of classes

// Definition and use of classes 
class MyInfo {
     //class Is the key word , Class names are all capitalized by default 
  name: string; // attribute 
  weather: string; // attribute 
  
  constructor(name: string, weather: string){
     // Constructors , Generally used to initialize . without ,TS It will automatically generate a , For backup new Call... When creating a class instance .
    this.name = name;
    this.weather = weather;
  }
  printInfo(): void {
     // Other functions , No return value 
    console.log(`Hello, ${
      this.name}.`);
    console.log(`Today is ${
      this.weather}.`);
  }
}
let myData = new MyInfo('Jon', 'raining'); // Use new Keywords generate objects , That is, an instance of this class 
myData.printInfo();

2. Class properties and function access rights

The properties and functions in the class have access rights , The default is public That is, globally accessible ;protected Is accessible within a class and its subclasses ;private Can only be accessed inside this class .

// Access right 
class MyInfo {
     
  public name: string; //public attribute , Omission 
  private _weather: string; // Private property , Get used to _ Name it at the beginning 
  
  constructor(name: string, weather: string){
     // Constructors , Generally used to initialize 
    this.name = name;
    this._weather = weather;
  }
  printInfo(): void {
     // Other functions 
    console.log(`Hello, ${
      this.name}.`);
    console.log(`Today is ${
      this._weather}.`);
  }
}

let myData = new MyInfo('Jon, 'raining'); // Use new Keywords generate objects 
console.log(myData._weather); //error!
myData.printInfo(); 

3. Accessors

TypeScript Supported by getter and setter To intercept access to object members , It can help you effectively control access to object members .
When outside a class , It is recommended to set getter and setter Operate it private attribute , Even if public attribute So it is .

//getter and setter
class MyInfo {
     
  private readonly _name: string; // Private property , No external access .readonly So that it can only be assigned at initialization , It cannot be changed later . 
  private _weather: string; // Private property 

  constructor(name: string, weather: string){
     // Constructors , Generally used to initialize 
    this._name = name;
    this._weather = weather;
  }
  get name(): string {
    
    return this._name;
  }
  set name(value: string) {
      //error! _name Yes readonly attribute 
    this._name = value;
  }
  get weather(): string {
    
    return this._weather;
  }
  set weather(value: string) {
    
    this._weather = value;
  } 
}
  
let myData = new MyInfo('Jon', 'raining'); // Use new Keywords generate objects 
console.log(myData._name, myData._weather);
myData._weather = 'sunny'; //OK
myData._name = 'Wang'; //error!
console.log(myData);
 readonly Keyword sets the property to read-only , Read only properties must be initialized in declarations or constructors .
  Only with get Without set The accessor of is automatically inferred as readonly.

4. Static attribute

static Keyword is used to define the data members of a class ( Properties and methods ) For static , Static members can call... Directly through the class name .

// Static attribute , Built in or custom , There is no need to new You can use 
console.log(Math.round(89.64)); //90
console.log(Math.pow(2, 8)); //256
class MyStaticClass {
    
  static place = 'Earth';
  static printInfo() {
    
    console.log('We have only one Earth!');
  }
}
console.log(MyStaticClass.place);  //Earth
MyStaticClass.printInfo();

5. Inherit

Class inheritance uses the keyword extends, Subclasses cannot inherit private members of the parent class except ( Methods and properties ) And constructor , Everything else can be inherited .

class Animal {
    
    //  When the parameter passed in by the constructor is added with “ Access control characters ”, The class attribute with the same name will be declared at the same time , And the assignment 
    constructor(public name: string) {
     }
    protected log(message: string) {
    
      console.log(message);
    }
    move(distanceInMeters: number = 0) {
            
      this.log(`${
      this.name} moved ${
      distanceInMeters}m.`);// Please note that name Where does it come from 
      this.log('==============');
    }
  }
  
  class Horse extends Animal {
    
    constructor(name: string) {
     
      super(name); //  adopt super Call the parent constructor 
    }
    run(distanceInMeters = 50) {
     // Own unique function 
      this.log("Clop, clop..."); 
      super.move(distanceInMeters); //  adopt super Call the superclass method 
    }
  }
  
  let tom: Horse = new Horse("Tommy");
  tom.run(66);

The execution result is :
 Insert picture description here

Be careful :TypeScript You can only inherit one class at a time , Inheriting multiple classes is not supported , but TypeScript Support multiple inheritance (A Inherit B,B Inherit C).

7、 ... and . modular Module

  • For large projects , We need to use modules to manage . Every .ts File is a module , adopt export To expose elements to external modules , adopt import To introduce modules .
  • Modules are self declared ; The relationship between the two modules is achieved by File level Upper use imports and exports The establishment of a .

The syntax is as follows :

//  file name  : SomeInterface.ts 
export interface SomeInterface {
     
   //  Code section 
}

To use this module in another file, you need to use import Keyword to import :

import someInterfaceRef = require("./SomeInterface");

8、 ... and . summary

TypeScript Our design solves JavaScript The problem of , Modularize the program , It helps us to develop large-scale programs .
in general TypeScript It's still easier , Because it's just JavaScript Extended syntax on . And the editor provides precise syntax hints , Let's practice object-oriented programming more easily .

Nine . Learning materials

https://typescript.bootcss.com/

原网站

版权声明
本文为[on the moon]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/177/202206252236011513.html