当前位置:网站首页>Introduction to typescript

Introduction to typescript

2022-06-11 19:29:00 PENGJUNQIAO

Typescript

English official website :https://www.typescriptlang.org/

Chinese official website :https://www.tslang.cn/

Introduce

TypeScript Is a strongly typed programming language , It originated in the use of JavaScript Big projects developed , because JavaScript The limitation of being a weakly typed language , It is difficult to be competent and maintain the development work of large projects . So Microsoft is 2012 Introduced in the TypeScript , Make it competent to develop large projects .

TypeScript By means of JavaScript It is built by adding static type definition on the basis of , Can be compiled as JavaScript Code to execute . It is characterized by a powerful type system and the ability to ES6 Specification support ,TypeScript Trusteeship in GitHub above .

ES6:ECMA2015/2016/2017 For short , It happens to belong to ECMA Of the 6 A version .
javascript:ECMA grammar ,BOM Browser object model and DOM Document object model .js Netscape is a browser side scripting language .
 European computer manufacturers association : abbreviation ECMA

characteristic

  • Type system : Type notes 、 Compile time type checking 、 Type inference and type erasure
  • Interface
  • enumeration
  • Mixin
  • Generic Programming
  • Namespace

from ECMA 6 It's transplanted from the specification :

  • class
  • modular
  • lambda Function arrow Syntax
  • Optional parameters and default parameters
  • Tuples 【 In fact, it is js From the array inside , It's just typescript It provides different ways to play , and python The Yuanzu in it is not the same thing 】
  • await / async

JavaScript And TypeScript Relationship and difference of

TypeScript Belong to Javascript Superset , Expanded Javascript The grammar of , The existing Javascript The code can be changed in TypeScript Operation in environment . meanwhile TypeScript Code , Can pass typescript The compiler is converted to pure JavaScript Code , And compiled JavaScript Code can run on any browser .TypeScript The compiler can also run on any server and any system .

typeScript The suffix of the file is .ts.

advantage

  • Most of the current popular code editors IDE Tools support typescript, Writing typescript Code , Than the original javascript Tips are more friendly .
    typescript The type system is equivalent to the best documentation, and is more transparent for the use of unfamiliar functions or classes , Understandability .
  • typescript The provided type system enhances the readability and maintainability of the front-end code , Most errors can be found ahead of time at compile time , Most type related errors can be locked ahead of time without project running .
  • Fully support es6 standard , Generated after compilation javascript The code can run on any browser , Solved each front-end browser to es6 The compatibility of specifications in different degrees .
  • There are active communities , Most third-party libraries are available for ts The type definition file of

shortcoming

  • It has a certain learning cost , Need to understand the interface 、 Generic Programming 、 Enumeration type and so on
  • Short term increase in development costs , In a native javascript On the basis of , Write more definitions of types .
  • Integration into the project build process requires some effort
  • And some of the existing javascript A combination of third-party libraries or frameworks exists bug

install

There are two main ways to get TypeScript Tools :

  • adopt npm(Node.js Package manager )
  • install Visual Studio Of TypeScript plug-in unit

Here it is , We go through npm To install / to update typescript

#  install 
npm install -g typescript
#  Update to the latest version 
npm update -g typescript
#  View version 
tsc -v

Quick start

establish typescript file

main.ts, Code :

function main(person) {
    return "Hello, " + person;
}

var user = "Jane User";

document.body.textContent = main(user);

Compile code

In the above code , Although we create script file is ts, But the code is real js Code . But because of typescript and javascript The relationship between , We can go straight through typescript The compiler compiles .

main.ts ---> compile (tsc)--> main.js

Terminal execution :

tsc main.ts
# tsc --out main.js main.ts  # --out  You can specify after compilation js file name 

After the command is executed, the output is a main.js file , It contains the same... As in the input file JavsScript Code .

although , In the process , We don't have access to typescript Code , But we have typescript Compiler usage . Is there any ?

Last , After compiling, we get js The file can go directly through script The label is html Use , In disguise , Equate to typescript It's used .

index.html, Code :

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <!-- async yes javascript stay ES6 New delay loading keyword  -->
    <script async src="main.js"></script>
</head>
<body>
	
</body>
</html>

Let's take a look at TypeScript Advanced functions brought by tools .

Type notes

main.ts, The code gives main The parameters of the function person add to : string Type notes , as follows :

function main(person: string) {
    return "Hello, " + person;
}

let user = "Jane User";

document.body.textContent = main(user);

you 're right , Do you feel a little familiar ? you 're right ,python3.5 The function of type annotation has also been added in later versions , Many in the new version python There are similar codes in the framework .

Terminal execution :

tsc main.ts

Try to put person The argument of the parameter is changed to pass in an array :

function main(person: string) {
    return "Hello, " + person;
}

let user = [0, 1, 2];

document.body.textContent = main(user);

recompile , You'll see that there was a mistake , Of course , similar pycharm In this way IDE Tools , There should be an error message already .

error TS2345: Argument of type 'number[]' is not assignable to parameter of type 'string'.

TypeScript Tell you , This function is called with an unexpected number of arguments . During the compilation process ,TypeScript Provides static code analysis , It can analyze the code structure and provide type annotations . Of course , Despite the compilation error ,main.js The file is still created . Even if there are errors in your code , You can still use TypeScript.

data type

data type keyword describe
Any type any If you don't declare a type , By default, it is declared as any Can be given any type of value .
value type number Equate to JavaScript Of number type , stay TypeScript All the numbers in are floating-point numbers , All are number type .
let num1: number = 0b1010; // Binary system
let num2: number = 0o744; // octal
let num3: number = 6; // Decimal system
let num4: number = 0xf00d; // Hexadecimal
Be careful :TypeScript and JavaScript There are no integers .
String type string A series of characters , Use single quotes (') Or double quotes (") To represent the string type . Use backquotes to define multiline text and embedded expressions .
let name: string = "xiaoming";
let qq_number: string= '50000000';
let text: string = Hello! , My name is ${ name } , my QQ The number is ${qq_number} ;
Boolean type boolean Only 2 It's worth :true and false.
let sex: boolean = true;
An array type nothing Declare variables as arrays .
let arr: number[] = [1, 2]; // After the element type, add []
let arr: Array = [1, 2]; // Array generics
Tuples nothing Tuple type is used to represent an array of known number and type of elements , The types of elements do not have to be the same , The type of the corresponding location needs to be the same . Yuanzu in the original js China itself is supportive .
let x: [string, number];
x = ['xiaoming', 16]; // Running normally
x = [16, 'xiaoming']; // Report errors
console.log(x[0]); // Output xiaoming
enumeration enum Enumeration types are used to define a collection of values .
enum Color {Red, Green, Blue};
let c: Color = Color.Blue;
console.log(c); // Output 2
void void The type used to identify the return value of a method , Indicates that the method does not return a value .
function hello(): void {
alert("Hello xiaoming");
}
null null empty .
undefined undefined Undefined
never never never It's other types ( Include null and undefined) Subtypes of , Represents a value that never appears .

I understand typescript Supported data types , In fact, we can be more clear that javascript There are , Can use the ,typescript There must be , And can also use . So in the next study , in the light of javascript and typescript We will explain the differences , The same default and javascript It's the same .

for example , Next, in grammar , Variable naming conventions , Operator , Flow control statements and so on , We won't talk about that .

Variable

Declaration of variables

// 1. When variables are declared , Directly specify the data type of the variable 
var  Variable name : type  =  value ;
// 2. Do not specify type , The default type is any
var  Variable name  =  value ; // var  Variable name :any =  value ;
// 3. Preset variables , Specify the type 
var  Variable name : type ;
// 4. Do not specify type and value , The default type is any,  The default value is  undefined:
var  Variable name ;

In development, the above 4 format , The most common is the second 3 Kind of , Code :

var username:string = "hello world";
username = "xiaoming";
username = 123;  // error TS2322: Type 'number' is not assignable to type 'string'.
console.log(username);

Variable scope

Variable scope refers to : The use scope and life cycle of variables are determined according to the position of variable definition .

TypeScript Three different scopes are provided :

  • Global scope
    Global variables are defined outside the program structure , It can be used anywhere in your code .

  • Class scope
    This variable can also be called Properties or fields .
    The head position of the class variable basic declaration in the class , Not only can it be called in the method of a class , It can also be outside of class methods , This variable can be accessed through the class name .
    Class variables can also be static variables , Static variables can be accessed directly through the class name .

  • Local scope
    local variable , A local variable can only be declared in one block of code ( Such as : Method ) Use in .

    var global_num = 12 // Global variables
    class Numbers {
    num_val = 13; // Instance variables
    static sval = 10; // Static variables

     storeNum():void { 
        var local_num = 14;    //  local variable 
     } 
    

    }
    console.log(" The global variable is : "+global_num)
    console.log(Numbers.sval) // Static variables
    var obj = new Numbers();
    console.log(" Instance variables : "+obj.num_val)

Joint type

//  grammar 
var  Variable  =  type 1| type 2| type 3|...;

//  Be careful :
//  Joint type (Union Types) You can go through the pipes (|) Set variables to multiple types , The assignment can be made according to the type of setting . Only the specified type can be assigned , If other types are assigned, an error will be reported .

Code :

//  Allow variables in use , Value can be one of the given types 
var age:string|number; //  Definition of joint type 

age = 20;
age = "20";

function sprint(data:string|number|any[]){
    console.log(data);
}

function abc(){
    return "hello!";
}

var num:number = 100;
sprint(num);

var uname:string = "xiaoming";
sprint(uname);

var arr:any[] = [100,"B","C"];
sprint(arr);

function

typescript and javascript In the declaration and use of functions , In addition to type annotations , There's no other difference . So in the next example , Just take the ordinary function as an example , As for anonymous functions , Arrow function (lambda function ), Closure function , Are all the same , So it won't be mentioned here .

Declaration of functions

//  Ordinary function 
function func_name( param1 [:type], param2 [?:type],param3[?]....) [:return_type]{
    
}

// lambda function 
var func = (param1:type) => expression;

/*
 type Represents the data type of the formal parameter , You can specify the type , You can also specify no type 
 return_type  Represents the data type of the return value after the function is executed , You can specify , Or not 
  The formal parameter is followed by ?, Indicates that the current parameter is optional , It can be filled but not filled 
 */

Code :

//  The definition of ordinary functions 
//  Parameters have 3 Kind of :
//  Required parameters [ You can qualify the type ]
//  Optional parameters  ?  [ You can qualify the type ]
//  Default parameters , Default values are provided ,[ You can qualify the type , Even if the type is not limited ,typescript The default value is also used to determine the type ]
function func1(arg1,arg2:number,arg3?,arg4?:string,arg5:string="xioaming"):void{
    console.log(`arg1=${arg1},arg2=${arg2},arg3=${arg3},arg4=${arg4},arg5=${arg5}`);
}
// javasctipt/typescript When reading code , branch 2 Everywhere 
//  From top to bottom , Do lexical detection , Identify keywords , Allocate space []
//  From top to bottom , Code execution 
func1(100,200);

//  here arg5 Result in an error , Because typescript The built-in type system includes type determination ,
//  In the parameter list at the time of function declaration , Have been to arg5 Assign default values , Because of this default value ,
//  therefore typescript according to arg5 The default value of is type determined , I recognized that it was string,
//  therefore , The parameter passed when calling the function is number It must be wrong 
// func1(100,200,300,"400",500);


//  Type determination 
// var data = " data ";
// data = 200;

//  Arrow function 
// var func = (num1:number,num2:number):number => {return num1+num2}; //  Native script Writing 
var func = (num1:number,num2:number):number => num1+num2; // typescript Expressions are allowed 
console.log( func(100,200) );

function overloading

Wrong writing :

function func1(str1:string):void{
    console.log(str1);
}

function func1(num1:any,str1?:any):void {
    console.log(num1);
    console.log(str1);
}
func1("hello");
func1(16,"hello");

Write it correctly :

function func1(str1:string):void;
function func1(num1:number,str1:string):void;

function func1(num1:string|number, str1?:string):void {
    console.log(`num1=${num1}`);
    console.log(`str1=${str1}`);
}

func1("hello");
func1(16,"hello");

class

Class declaration, use and inheritance

class Humen {
    age:number = 12; //  Instance attributes 
    constructor(age?:number) { //  Initialization method , similar python Of __init__
      if(typeof age == "number"){
          this.age = age;
      }
    }
    desc():string {
       return ` I this year ${this.age} year `;
    }
}

// var xiaoming:Humen = new Humen();
// console.log(xiaoming.age);
// // xiaoming.age = 100;
// console.log(xiaoming.desc());

class Person extends Humen{
    uname:string;
    desc():string{
     return ` My name is ${this.uname},`+super.desc();
    }
}

var xm = new Person(18);
console.log(xm.age);
xm.uname = " Xiao Ming ";
console.log(xm.desc());

In inheritance , You can override the parent method , Include constructors , Code :

//  Public attribute :  Allow anywhere to call 
//  Private property :  Only calls inside the current class are allowed 
//  Protection properties :  Only the current class or the subclass that directly or indirectly inherits the current class can be called inside 
class Proto{
    private name:string;
    public constructor(name:string){
        this.name=name;
    }
}

class Humen extends Proto{
    private age:number;
    public constructor(name:string,age?:number){
        super(name);
        this.age = age;
    }
}

class People extends Humen{

}

var p1 = new People("xiaoming",13);
console.log(p1);

Static properties and methods

class Static {
   //  Static attribute 
   static num:number;
   //  Static methods 
   static desc():void {
      console.log("num  The value is  "+ Static.num)
   }
}
//  There is no need to instantiate the object , You can call through the class 

Static.num = 12;     //  Initialize static properties / Variable 
Static.desc();       //  Call static methods 

Access control character

Encapsulation in object-oriented , It's essentially a series of related data ( attribute / Variable / Field ) And how to manipulate data ( Method / function ) Centralize into one data structure ( class ), Methods to hide and manipulate data , Methods of operating data with limited exposure .

TypeScript in , You can use access controls to protect pairs of classes 、 Variable 、 Access to methods and constructors .TypeScript Support 3 Different access rights .\

  • public( Default ) : public , Can be visited anywhere .
  • protected : The protected , Can be accessed by itself and its subclasses and parents .
  • private : private , Can only be accessed by the class in which it is defined .

Code :

//  Public attribute :  Allow anywhere to call 
//  Private property :  Only calls inside the current class are allowed 
//  Protection properties :  Only the current class or the subclass that directly or indirectly inherits the current class can be called inside 
class Proto{
   public desc(){                   //  Public methods 
      return ` I live in a tree `;
   }
}

class Humen extends Proto{
   public address:string = " The Beijing municipal "; //  Public attribute 
   public desc(){                   //  Public methods 
      return ` I live in ${this.address}`;
   }

   private money:number = 10000;    //  Private property 
   private calc_money(){
      return this.money*0.1;  //  Private properties can only be called inside a class , Private method 
   }
   //  If you allow private properties to be provided to the outside world ,  Exposure is often done through public means 
   public show_money(){
      return this.calc_money();
   }

   protected phone:string = "13300000000";  //  Protection properties 
   protected get_phone(){                   //  Protection method 
      return ` my cellphone number :${this.phone}`; //  Only the inner or subclass of a class can call protection properties / Method 
   }
   //  If you allow protected properties to be viewed by the outside world , Exposure is often done through public means 
   public show_phone(key?){
      if(key == "123456"){
         return this.get_phone();
      }
   }
}

class People extends Humen{
   public show_father_data(){
      // return this.phone;    //  Called the protection property of the parent class 
      // return this.get_phone(); //  Called the protection method of the parent class 

      return this.show_money();       //  A subclass cannot call a private property or method of a parent class 

      // return this.desc();  //  Call the inherited parent class method or property , If the current class is overloaded, an override appears 
      // return super.desc();
   }

   public desc(){
      return ` Hello! ,  I live in ${this.address}`;
   }

}

var xiaoming = new People();
// console.log(xiaoming.phone); //  Private or protected properties cannot be called outside of a class 
// console.log(xiaoming.address);
// console.log(xiaoming.desc());
// console.log(xiaoming.show_money());
// console.log(xiaoming.show_phone());
// console.log(xiaoming.show_phone(123456));
console.log(xiaoming.show_father_data());

Accessors

class Humen{
    private _money: number; //  Private property 
    constructor(money:number) {
        this._money = money;
    }
    
    public set money(money:number) { //  Memory 
        this._money= money;
    }
    
    public get money(): number { //  Reader 
        return this._money;
    }
}

var xm = new Humen(10000);
console.log(xm.money);  //  Call the reader to access the data 
xm.money = xm.money - 300; //  Call memory to save data ,xm.money-300 Provide to set Memory as a parameter 
console.log(xm.money);

python Accessor in

class Money(object):
    _money = 0
    def __init__(self,money):
        self._money = money

    #  Use decorator pairs money Decorate , So it will automatically add a name money Properties of , When called get money The value of , Invokes the decorated method 
    @property
    def money(self):
        return self._money

    #  Use decorator pairs money Decorate , When the money When the set values , Invokes the decorated method 
    @money.setter
    def money(self, value):
        if isinstance(value, int):
            self._money = value
        else:
            print("error: It's not an integer number ")

if __name__ == '__main__':
    a = Money(100)
    print(a.money)

Interface

Interface (interface) Is a collection declaration of a series of abstract properties and methods , These methods should be abstract , It needs to be implemented by specific classes , Then the outside world can call through this set of abstract methods , Let specific classes execute specific methods .

The function of interface is to describe and standardize the structure of data objects and classes in development . To put it bluntly , Your boss asked you to declare a class / object , But this class / What does the object look like ? He will define it in the format of interface first , Then you write a class in the format defined by the interface / The object comes out , So you don't mess up the structure , You can't reuse code in the future .

Generally only in medium and large projects , Or frame / In order to better organize the code structure, abstract classes will appear in large modules / Interface

Defining interfaces

interface PayTool {
    SERVER_URL:string;
    pay: ()=>string
}

Declaration and implementation of interface

interface PayTool {
    SERVER_URL:string;
    pay: ()=>string;
}

class Alipay implements PayTool{
    SERVER_URL:string;
    constructor(server_url:string){
        this.SERVER_URL = server_url
    }
    pay(){
        return "ok"
    }
}

class WechatPay implements PayTool{
    SERVER_URL:string;
    constructor(server_url:string){
        this.SERVER_URL = server_url;
    }
    pay(){
        return "ok"
    }
}

var alipay = new Alipay("http://api.alipay.com");
console.log(alipay);
console.log( alipay.pay() );

All realized (implements) The interface is completed / Classes of abstract classes , It has to be connected to the interface / Abstract classes keep having the same properties and methods

Shorthand implementation of interface

typescript Allow direct passage through json Object to directly implement the interface , Skipping class implementation

interface Person {
    username: string;
    age: number;
    desc():string
}

function main(person: Person) {
    return "Hello,  My name is " + person.username + ", I this year " + person.age+" year .";
}

// typescript Allows you to implement interfaces directly through objects , Skipping class implementation 
// var  Object name  = < The name of the interface >{
//     attribute ;
//     Method ;
// }
let user = <Person>{
   username: " The small white ",
   age: 16,
   desc(){
      return "hello"
   }
};
console.log(main(user));
// js It's a functional programming language in an object-oriented shell 

The duck type

When passing instance parameters , Whether or not the currently passed in instance parameter is a qualified class / Instance object of interface , As long as they have the same attributes / Method , Then we think that the current instance parameter is the qualified class / Instance object of interface . This is the so-called duck type .

//  The duck type :
//  The duck type specifies :  Effective semantics of an object , Not determined by inheriting from a specific class or implementing a specific interface ,
//  But by the " A collection of methods and properties of the current object " decision 

interface Person {
    username: string;
    age: number;
}

function main(person: Person) {
    return "Hello,  My name is " + person.username + ", I this year " + person.age+" year .";
}

var xm = {username:" Xiao Ming ",age:20}; //  The problem is coming. , It's not true here Person Interface , Why can I call 
console.log(main(xm));

python The duck type in

class Person(object):
    def __init__(self,username,age):
        self.username = username
        self.age = age

class Humen(object):
    def __init__(self,username,age):
        self.username = username
        self.age = age

def main(obj:Person):
    return " My name is %s, I this year %s Year old " % (obj.username,obj.age)

if __name__ == '__main__':
    p1 = Person(" Xiao Ming ", 15)
    p2 = Humen(" The small white ", 15)
    print( main(p2) )

Interface inheritance

Single inheritance

interface Person {
   age:number
}

interface Humen extends Person {
   username:string
   desc(user:string):string
}

class People implements Humen{
   age:number;
   username:string;
   constructor(username,age){
      this.age = age;
      this.username=username;
   }
   desc(user:string):string{
      return `${user}, Hello! ! My name is ${this.username}, I this year ${this.age} year .`
   }
}

var xm = new People(" Xiao Ming ",15);
console.log( xm.desc(" Xiaohong ") );

Multiple inheritance

interface Person {
   age:number
}

interface Humen{
   username:string
   desc(user:string):string
}

//  Multiple interfaces can be implemented at the same time 
class People implements Person, Humen{
   age:number;
   username:string;
   constructor(username,age){
      this.age = age;
      this.username=username;
   }
   desc(user:string):string{
      return `${user}, Hello! ! My name is ${this.username}, I this year ${this.age} year .`
   }
}

var xm = new People(" Xiao Ming ",15);
console.log( xm.desc(" Xiaohong ") );

abstract class

abstract class (abstract class) Use as a base class for other derived classes . They are generally not instantiated directly . Unlike interfaces , Abstract classes can contain implementation details of members . abstract Keywords are used to define abstract classes and abstract methods within abstract classes .

Code :

//  Abstract parent class 
abstract class Animal{
   abstract makeSound(): void;        //  Abstract method , There is no function body 
   desc(): void {   //  Public methods or properties of subclasses can also be defined in abstract classes 
      console.log('roaming the earch...');
   }
}

//  Abstract parent class 
abstract class Dog extends Animal{
   abstract nickname:string;
   abstract move(): string;
}


//  Concrete class / concrete class 
class ChineseGardenDog extends Dog{
   public nickname:string;
   constructor(nickname:string){
      super(); //  Inherits subclasses of abstract classes , The parent class must be initialized 
      this.nickname = nickname;
   }
   makeSound(){
        return " Wang Wang Wang ~"
   }
   move(): string {
      return " Running ....";
   }
}

var dog = new ChineseGardenDog(" Laifu ");
console.log(dog.nickname);
console.log(dog.makeSound());

python Abstract classes in

stay python There are no abstract class and interface concepts in the basic syntax of . therefore , To implement scenarios similar to interfaces or abstract classes , Can use python Built in standard library ,abc Module to achieve .

import abc  #  utilize abc Modules implement abstract classes 

class File(metaclass=abc.ABCMeta):  # abc.ABCMeta It is a basic class to implement abstract classes 
    @abc.abstractmethod  #  Define abstract methods , There's no need to implement functions 
    def read(self):
        pass


class Txt(File):  #  Subclass inherits abstract class , But it has to be defined read Method abstracts the read Methods cover 
    def read(self):
        print(' Reading method of text data ')


if __name__ == '__main__':
    txt1 = Txt()
    txt1.read()
    #  Abstract classes cannot be instantiated directly 
    tet2 = File()
    tet2.read()

Decorator

With TypeScript and ES6 Class is introduced in , In some scenarios, we need additional features to support annotation or modification of classes and their members . Decorator (Decorators) It provides a way for us to add annotations through metaprogramming syntax on class declaration and members . A decorator is a special type of statement , It can be attached to a class declaration , Method , The accessor , Property or parameter .

Code :

function derator1() {
    console.log(`derator1()`);
    function wrapper(target, propertyKey: string, descriptor: PropertyDescriptor) {
        console.log(`derator1()`);
    }
    return wrapper
}

function derator2(key:string) {
    console.log(`derator2()`);
    function wrapper(target, propertyKey: string, descriptor: PropertyDescriptor) {
        console.log(`derator2()`);
    }
    return wrapper
}

class Demo {
    @derator1()
    @derator2("abc")
    show(username:string,password:string) {
        console.log("show() Yes ");
    }
}

var d = new Demo();
d.show("xioaming","123456");

Because the decorator is ES7 The content in , So by default , therefore tsc It is not supported by default during compilation , therefore , We need to compile the code es Convert version to es5 And enable the function of supporting decorator during code compilation .

Official documentation :https://typescript.bootcss.com/decorators.html

The terminal runs as follows :

tsc --target ES2020 --experimentalDecorators --emitDecoratorMetadata main.ts

Namespace

When the project is big , Functions that need to be created and declared , There are more classes , There are more natural people , Too many people are bad things . Think about the number of three in the country ?

Namespace (namespace) One of the most explicit purposes is to solve the problem of duplicate names .

The namespace defines the visible range of identifiers , An identifier can be defined in more than one namespace , Its meaning in different name spaces is irrelevant . such , Any identifier can be defined in a new namespace , They don't conflict with any existing identifiers , Because the existing definitions are all in other namespace .

Define the namespace

app.ts, Code :

//  The name of the namespace is humped 
namespace App{ 
    //  You need to call... Outside of the namespace   The class of the current namespace , Functions and interfaces, etc , You need to add... To the left  export  keyword .
    //  Variable 
    export var username:string="App Variables of space ";
    //  Constant , Once defined , Can't change value 
    export const NAME = "App Constants for the namespace ";
    //  function 
    export function func(){
        return "App In the namespace func"
    }
    //  class 
    export class Humen{

    }
    //  Of course , Code can also be executed in the current namespace     
}

Import namespace

main.ts, Code :

Import other namespace formats :/// , You can import multiple namespace , A line of one .

/// <reference path="app.ts" />
console.log(App.func());  //  Call the contents of another namespace , Must be " The name of the namespace .xxxx" Format 
console.log(App.NAME);
console.log(App.username);
console.log(new App.Humen());

After using the namespace , The compilation command needs to be slightly adjusted as follows :

tsc --out main.js main.ts  #  Must specify --out Parameters to compile properly 

modular

TypeScript The design concept of modules is replaceable organization code . Modules are executed in their own scope , Not in the global scope , This means that the variables defined in the module 、 Functions, classes, etc. are not visible outside the module .

typescript Two modules are provided : Internal and external modules , Because external modules need to rely on third-party frameworks to be used , for example :commonjs,requirejs etc. . So here , Let's just briefly introduce the declaration and use of internal modules .

Internal modules

Declaration module

app.ts, Code :

module App{
    export class Humen {
        desc(){
            console.log("hello");
        }
    }

    export function func(){
        console.log("hello, func");
    }

}

Call module

main.ts, Code :

module App{ //  Module name , Use the big hump writing method 
    //  Allow other modules to call the contents of the current module , Then use export Expose 
    export class Humen {
        desc(){
            console.log("hello,Humen.desc");
        }
    }

    export function func(){
        console.log("hello, func");
    }

}

After using the internal module , The compile command is the same as the namespace :

tsc --out main.js main.ts

External modules

Out.ts, Code :

class Humen{
    uname:string;
    constructor(uname){
        this.uname = uname;
    }
    desc() {
        return ` Hello! , My name is  ${this.uname}`;
    }
}
export { Humen };
export { Humen as People };

The import module ,main.ts, Code :

import { Humen, People } from "./Out";

let obj1 = new Humen(" The small white ");
let obj2 = new People(" Little black ");
obj1.desc();
obj2.desc();

Compile command :

tsc --module es6 main.ts   # --module  Represents the specifications and standards for writing modules in code 

Compile configuration file

be based on typescript Development project root , There is usually a file , It's called tsconfig. This is a typescript Build configuration file for .

configuration option :https://www.tslang.cn/docs/handbook/compiler-options.html

tsconfig.json, Description of common configuration items , Code :

//  The current profile name must be fixed to : tsconfig.json
//  meanwhile ,json Comments cannot appear in the file , So the notes here are just for learning , There must be no... In development 
{
    "compilerOptions": {
        "module": "system",     //  The standard for writing modules in a project 
        "noImplicitAny": true,  //  There is an implicit... In an expression or declaration  any Wrong type 
        "removeComments": true, //  Delete all comments , Except for  /!* Copyright information at the beginning .
        "preserveConstEnums": true,  //  Retain const and Enums Statement 
        "outDir": "script",  //  The compilation result is saved in the directory 
        // "outFile": "../../built/local/tsc.js",  //  Compiled output file , It doesn't usually work 
        "sourceMap": true,  //  Generate corresponding  .map file 
        "experimentalDecorators": true,  //  Enable experimental ES Decorator 
        "lib": [ //  List of library files to be imported during compilation 
            "es5",
            "dom",
            "es2015.promise"
        ]
    },
    "files": [   //  Specify the list of files to compile ,  And include and exclude Conflict , In development , In general use exclude
      "main.ts"
    ]
  //    "include": [ //  Specify the directory of the file to be compiled 
////        "src/**/*",
//        "./"
//    ],
//    "exclude": [ //  Specifies the file directory to exclude at compile time 
//        "node_modules",
//        "**/*.spec.ts"
//    ]
}

An analytic expression

function getStock() {
    return {
        code: "IBM",
        price: 100
    }
}
    
var stock = getStock(); //ES5 Writing 
var code = stock.code;  //ES5 Writing 
var price = stock.price;//ES5 Writing 


//  The writing method of deconstruction expression 
//  The effect is the same as the above ES5 In the same way 
var { code, price } = getStock();

//  You can also use an alias , such as 
var { code :aaa, price} = getStock();
console.log(aaa);// In this case aaa It can also be printed 

Generic

The main function of generics is to parameterize data types , Ensure consistency in the use of data , Let's write more reusable code , And more flexible .

Generic functions

function identity<T>(arg: T): T {
    return arg;
}

function loggingIdentity<T>(arg: Array<T>): Array<T> {
    console.log(arg.length);
    return arg;
}

Generic variables

function identity<T>(arg:T):T{
    console.log(typeof arg);
    return arg;
}
let output1=identity<string>('myString');
let output2=identity('myString');
let output3:number=identity<number>(100);
let output4:number=identity(200);

The generic type

let myIdentity: Array<T>;

function identity<T>(arg: T): T {
    return arg;
}

let myIdentity: {<T>(arg: T): T} = identity;

Generic interface

interface GenericIdentityFn {
    <T>(arg: T): T;
}

function identity<T>(arg: T): T {
    return arg;
}

let myIdentity: GenericIdentityFn = identity;

Generic classes

class GenericNumber<T> {
    zeroValue: T;
    add: (x: T, y: T) => T;
}

let myGenericNumber = new GenericNumber<number>();
myGenericNumber.zeroValue = 0;
myGenericNumber.add = function(x, y) { return x + y; };

Generic constraint

interface Lengthwise {
    length: number;
}

function loggingIdentity<T extends Lengthwise>(arg: T): T {
    console.log(arg.length);
    return arg;
}

loggingIdentity({length: 10, value: 3});


function showKey<K extends keyof T, T> (items: K[], obj: T): T[K][] { // T[K][]  by K An array of types , And meet K by T Of key
    return items.map(item => obj[item])
}

generator

generator

function* getStockPrice(stock){
	
  while(true){
  	yield Math.random()*100;
  }
  
}
 
var priceGenerator = getStockPrice()
 
var limitPrice = 15;
 
var price = 100;
 
while(price > limitPrice){
  price = priceGenerator.next().value;
  console.log(`the generator reutrn ${price}`);
}
 
console.log(`buying at ${price}`)

Python Type annotation of

typing modular

since python3.5 Start ,PEP484 by python Type annotation is introduced (type hints)

  • Type checking , Prevent parameter and return value types from appearing at run time 、 Variable type does not match .
  • As a development document , It is convenient for the user to pass in and return parameter types when calling .
  • The addition of this module will not affect the operation of the program , Don't report a formal mistake , Only reminders .
    pycharm At present, we support typing Check , If the parameter type is wrong, a yellow prompt will appear .

Common types

  • int,long,float: integer , Long plastic surgery , floating-point
  • bool,str: Boolean type , String type
  • List, Tuple, Dict, Set: list , Tuples , Dictionaries , aggregate
  • Iterable,Iterator: Iterative type , Iterator type
  • Generator: Generator type

The basic type specifies

Code :

from typing import List,Dict,Tuple,Union
#  integer 
num:int = 100
#  character string 
data:str = "200"
#  Boolean value 
bo:bool = True
#  list 
data_list:List[str] = ["1","2","3"]
#  Dictionaries 
data_dict:Dict[str, str] = {"name":"xiaoming",}
#  Tuples [ Limit data and types ]
data_tuple:Tuple[int,int,bool] = (1,2,False)

#  Joint type [ Generic ]
U1 = Union[str,int] #  It can only be a string or an integer 
data_union1:U1 = "20"
data_union2:U1 = 200
data_union3:U1 = [1,2,3]  #  It doesn't meet the requirements here , Yellow prompt appears 

def test(a:int, b:str) -> str:
    print(a, b)
    return 1000

if __name__ == '__main__':
    test('test', 'abc')

"""
 function test,
a:int   Input parameters are specified a by int type ,
b:str  b by str type ,
-> str   The return value is srt type .

 You can see ,
 In the method , We finally returned to a int, here pycharm There will be a warning ;
 When we call this method , Parameters a We're entering a string , There will also be warnings ;
 But it's very important that ,pycharm It's just a warning , But in fact, the operation will not report an error , After all python The essence of language is dynamic language 
"""

Complex type annotation

Code :

from typing import List
Vector = List[float]

def scale(scalar: float, vector: Vector) -> Vector:
    return [scalar * num for num in vector]

#  Type determination :  The data that is being transferred is just like Vector The format is just , This is also the result of duck type .
new_vector = scale(2.0, [1.0, -4.2, 5.4])

Code :

from typing import Dict, Tuple, Sequence

ConnectionOptions = Dict[str, str]
Address = Tuple[str, int]
Server = Tuple[Address, ConnectionOptions]

def broadcast_message(message: str, servers: Sequence[Server]) -> None:
    ...

# The static type checker will treat the previous type signature as
# being exactly equivalent to this one.
def broadcast_message(
    message: str,
    servers: Sequence[Tuple[Tuple[str, int], Dict[str, str]]]) -> None:
    ...
):
    ...
"""
 Here we need to pay attention to , Tuple is a special type , Because it's immutable .
 therefore , When we specify Tuple[str, str] when , You can only pass in a length of 2,
 And all the elements in the tuple are str type 
"""

Specify a generic type

Code :

from typing import Sequence, TypeVar

T = TypeVar('T')      #  Define generic variables , It can be any kind of data 
b2:T = True # b2 The value of can be any type of data 

def first(l: Sequence[T]) -> T:   # Generic function
    return l[0]

A = TypeVar('A', bool, str, bytes)  #  The scope of the current generic can only be a string or bytes type 
b3:A = "hello"
b4:A = "hello".encode()
b5:A = True

Type assignment when creating variables

Code :

from typing import NamedTuple

class Employee(NamedTuple):
    name: str
    id: int = 3

employee = Employee('Guido')
assert employee.id == 3

deficiencies : Prompt for errors without affecting execution

Code :

from typing import List

def test(b: List[int]) -> str:
    print(b)
    return 'test'


if __name__ == '__main__':
    test([1, 'a'])

"""
 As you can see from this example , Although we have designated List[int] by int A list of components ,
 however , In the actual , As long as it's in this list nt( Others can be of any type ), There would be no warning 
"""
原网站

版权声明
本文为[PENGJUNQIAO]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/03/202203011826134496.html