当前位置:网站首页>Tell the truth of TS

Tell the truth of TS

2022-04-23 17:44:00 Front Thoughts

 Insert picture description here

typescript What the hell is that? ------- ghost who stays among the living !!!

from JavaScript Language limitations , Difficult to maintain large projects , So there is TypeScript , It's a kind of giving JavaScript Language extensions to add features . Grammatically similar JScript .NET, Another one added to the static type , Classic object-oriented language features such as classes , Inherit , Interface, namespace, etc Microsoft Yes ECMAScript Implementation of language standards .

TypeScript yes JavaScript A superset of . By default, the compiler uses ECMAScript 3 (ES3) For the goal, but ES5 It's also a supported option . One TypeScript Applications can take advantage of existing JavaScript Script . The compiled TypeScript Scripts can also be from JavaScript Use in .

Existing frameworks such as jQuery and Node.js Wait for full support . The type declarations for these libraries are provided in the source code . Supported browsers and platforms any web browser running on any platform can run TypeScript Because it's just compiled into standard JavaScript. A script can be precompiled into JavaScript It can also be done for TypeScript contain JavaScript The compiler compiles in real time .
 Insert picture description here
TypeScript Expanded JavaScript Syntax of , So any existing JavaScript The program can be in TypeScript Work under the .TypeScript It is designed for the development of large-scale applications , When compiled, it produces JavaScript To ensure compatibility .

install TypeScript

npm install -g typescript 

compile TypeScript file

tsc app.ts # app.ts => app.js

TypeScript data type

Boolean type

let isDone: boolean = false; // tsc => var isDone = false;

Number type

let count: number = 10;  // tsc => var count = 10

String type

let name: string = 'Semliker'; // tsc => var name = 'Semlinker'

mark Array type

let list: number[] = [1,2,3]; // tsc => var list = [1,2,3];   

let list: Array<number> = [1,2,3]; 
// tsc => var list = [1,2,3];

Enum type

enum Direction {
    
    NORTH,
    SOUTH,
    EAST,
    WEST
}; 

let dir: Direction = Direction.NORTH; 

Any ( Dynamic type )

let notSure: any = 4;
notSure = "maybe a string instead";
notSure = false; 

=> tsc =>  

var notSure = 4;
notSure = "maybe a string instead";
notSure = false;

Void

To some extent ,void The type is like with any The type is the opposite , It means there is no type . When a function does not return a value , You will usually see that the return value type is void:

//  Declare that the return value of the function is void
function warnUser(): void {
     
    console.log("This is my warning message");
}

=> tsc =>  

function warnUser() {
    
    console.log("This is my warning message");
}  

It should be noted that , Make a statement void Variables of type have no effect , Because its value can only be undefined or null:

let unusable: void = undefined;

Tuple

Tuple type allows you to represent an array of known elements and types , The types of elements do not have to be the same . such as , You can define a pair of values as string and number Tuples of type .

let x: [string, number];

x = ['semlinker', 10]; //  Normal assignment 

x = [10, 'semlinker']; //  Type mismatch 

When accessing an element of a known index , Will get the right type :

console.log(x[0].substr(1)); // OK

// Error, 'number' does not have 'substr' method
console.log(x[1].substr(1));

When accessing a cross-border element , Will use union type instead of :

x[3] = 'world'; // OK,  A string can be assigned to (string | number)  type 

console.log(x[5].toString()); // OK, 'string'  and  'number'  There are  toString  Method 

x[6] = true; // Error,  Boolean is not (string | number)  type 

TypeScript Assertion

Sometimes you come across a situation like this , You will be better than TypeScript Learn more about a value . Usually this happens when you know clearly that an entity has a more exact type than its existing type .

This way, you can tell the compiler ,“ believe me , I know what I'm doing ”. Type assertions are like type conversions in other languages , But no special data checking and deconstruction . It has no runtime impact , It only works during the compilation phase .

There are two forms of type assertion :

  • List item
let someValue: any = "this is a string";
let strLength: number = (<string>someValue).length;
  • as grammar
let someValue: any = "this is a string";
let strLength: number = (someValue as string).length;

TypeScript Union Types and Type Aliases

Union Types

let greet = (message: string | string[]) => {
    
  if(message instanceof Array) {
    
    let messages = "";
    message.forEach((msg) => {
    
      messages += ` ${
     msg}`;
    });
    console.log("Received messages ", messages);
  } else {
    
    console.log("Received message = ", message);
  }
};

greet('semlinker');
greet(['Hello', 'Angular']);

Type Aliases

type Message = string | string[];
let greet = (message: Message) => {
     
  // ... 
};

TypeScript Function

TypeScript Function and JavaScript Difference of function
 Insert picture description here

Arrow function

  • Common grammar
myBooks.forEach(() => console.log('Done reading'));

myBooks.forEach(title => console.log(title));

myBooks.forEach((title, idx, arr) => 
  console.log(idx + '-' + title);
);

myBooks.forEach((title, idx, arr) => {
    
  console.log(idx + '-' + title);
});
  • Examples of use
//  No arrow function used 
function Book() {
    
  let self = this;
  self.publishDate = 2016;
  setInterval(function() {
    
    console.log(self.publishDate);
  }, 1000);
}

//  Use the arrow function 
function Book() {
    
  this.publishDate = 2016;
  setInterval(() => {
    
    console.log(this.publishDate);
  }, 1000);
}

Parameter type and return type

function createUserId(name: string, id: number): string {
    
  return name + id;
}

Function type

let IdGenerator: (chars: string, nums: number) => string;

function createUserId(name: string, id: number): string {
    
  return name + id;
}

IdGenerator = createUserId;

Optional parameters and default parameters

//  Optional parameters 
function createUserId(name: string, age?: number, 
  id: number): string {
    
    return name + id;
}

//  Default parameters 
function createUserId(name: string = 'Semlinker', age?: number, 
  id: number): string {
    
    return name + id;
}

The remaining parameters

function push(array, ...items) {
    
  items.forEach(function(item) {
    
    array.push(item);
  });
}

let a = [];
push(a, 1, 2, 3);

TypeScript Array

  • An array of deconstruction
let x: number, let y: number ,let z: number;
let five_array = [0,1,2,3,4];
[x,y,z] = five_array;
  • Array expansion operator
let two_array = [0,1];
let five_array = [...two_array,2,3,4];
  • Array loop
let colors: string[] = ["red", "green", "blue"];
for(let i in colors) {
    
  console.log(i);
}

TypeScript Object

  • Object to deconstruct
let person = {
    
  name: 'Semlinker',
  gender: 'male'
};

let {
    name, gender} = person;
  • Object expansion operators
let person = {
    
  name: 'Semlinker',
  gender: 'male',
  address: 'Xiamen'
};

//  Assemble objects 
let personWithAge = {
    ...person, age: 31};

//  Get items other than some 
let {
    name, ...rest} = person;

TypeScript Interface

In object-oriented languages , Interface (Interfaces) It's a very important concept , It's an abstraction of behavior , And the specific action needs to be done by class (classes) To achieve (implements).

TypeScript The interface in is a very flexible concept , In addition to being able to abstract part of a class's behavior , It's also often used to correct 「 The shape of the object (Shape)」 Describe .

  • The shape of the object
interface Person {
    
  name: string;
  age: number;
}

let semlinker: Person = {
    
  name: 'Semlinker',
  age: 31
};
  • Optional | Read-only property
interface Person {
    
  readonly name: string;
  age?: number;
}

TypeScript Class

In object-oriented languages , Class is a construction of object-oriented computer programming language , Is the blueprint for creating objects , Describes the common properties and methods of the created objects .

stay TypeScript in , We can go through Class Keyword to define a class :

class Greeter {
    
   static cname: string = 'Greeter'; //  Static attribute 
   greeting: string; //  Member line 

   constructor(message: string) {
     //  Constructors  -  Perform the initialization operation 
     this.greeting = message;
   }

    static getClassName() {
     //  Static methods 
      return 'Class name is Greeter';
    }
    
    greet() {
     //  Member method 
      return "Hello, " + this.greeting;
    }
}

let greeter = new Greeter("world");

TypeScript Accessors

stay TypeScript in , We can go through getter and setter Methods to achieve data encapsulation and validation , Prevent the occurrence of abnormal data

let passcode = "hello angular 5";

class Employee {
    
    private _fullName: string;

    get fullName(): string {
    
        return this._fullName;
    }

    set fullName(newName: string) {
    
        if (passcode && passcode == "hello angular 5") {
    
            this._fullName = newName;
        }
        else {
    
            console.log("Error: Unauthorized update of employee!");
        }
    }
}

let employee = new Employee();
employee.fullName = "Bob Smith";
if (employee.fullName) {
    
    console.log(employee.fullName);
}

TypeScript Inheritance

Inherit (Inheritance) It's a hierarchical model that connects classes and classes . It refers to a class ( Called subclass 、 A subinterface ) Inherit another class ( Called the parent class 、 The parent interface ) The function of , And the ability to add its own new features , Inheritance is the most common relationship between classes or interfaces ; Inheritance is a kind of is-a Relationship .
 Insert picture description here
stay TypeScripe in , We can go through extends Keyword to implement inheritance :

class Animal {
    
    name: string;
    constructor(theName: string) {
     this.name = theName; }
    move(distanceInMeters: number = 0) {
    
        console.log(`${
     this.name} moved ${
     distanceInMeters}m.`);
    }
}

class Snake extends Animal {
    
    constructor(name: string) {
     super(name); }
    move(distanceInMeters = 5) {
    
        console.log("Slithering...");
        super.move(distanceInMeters);
    }
}

let sam = new Snake("Sammy the Python");
sam.move();

TypeScript Generics

Generic (Generics) Is a template that allows the same function to accept different types of parameters . Compared to using any type , It's better to use generics to create reusable components , Because generics preserve parameter types .

  • Generic interface
interface GenericIdentityFn<T> {
    
    (arg: T): T;
}
  • 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; };
  • Examples of use
interface Hero {
     // Hero  Interface 
    id: number;
    name: string;
}

getHeroes(): Observable<Hero[]> {
    
  return Observable.of([
     {
     id: 1, name: 'Windstorm' },
     {
     id: 13, name: 'Bombasto' },
     {
     id: 15, name: 'Magneta' },
     {
     id: 20, name: 'Tornado' }
  ]);
}

above getHeroes(): Observable<Hero[]> Represents a call to getHeroes() Method returns a Observable object ,<Hero[]> Used to indicate that Observable The observer of the object , The type of data that will be received . In the example, it means that <Hero[]> List of Heroes .

tsconfig.json brief introduction

tsconfig.json The role of

  1. Used to identify TypeScript The root path of the project
  2. Used for configuration TypeScript compiler
  3. Used to specify the compiled file

tsconfig.json Important fields

  1. files - Set the name of the file to compile
  2. include - Set the file that needs to be compiled , Support path pattern matching
  3. exclude - Set up files that do not need to be compiled , Support path pattern matching
  4. compilerOptions - Set options related to the compilation process

tsconfig.json - compilerOptions

Field explain
target Desired ECMAScript version (es3,es5,es2015,es2016,es2017, or esNext)
rootDir Root directory of input files
listFiles Print file names processed by the compiler
outDir Directory to contain compiled results
outFile File to contain concatenated results
watch Watch input files
removeComments Remove comments from generated output
noLib Don’t include the main library, lib.d.ts, in the compilation process
alwaysStrict Specifies whether strict mode should be enabled
noEmitOnError Don’t generate output if any errors were encounted
noImplicitThis Raise an error on this expressions with implied any type
noUnuseLocals Report errors on unused parameters
noImplicitAny Print a warning for every variable that isn’t explicitly declared
suppressImplicit Any IndexErrors Suppress Implicit AnyIndexError
skipLibCheck Suppress type checking of declarations files
experimental Decorators Enable support for ES7 decorators
declaration Generate declaration file(*.d.ts) for the TypeScript code
declarationDir Place declaration files in the given directory
module The formate of the generated module (commonjs, amd, system, umd, or es2015)
noEmitHelpers Do not insert custom helper functions in generated output
emitDecoratorMetadata Insert metadata for TypeScript decorations
isolatedModule Always insert imports for unresolved files
jsx Generate JSC code (preserve or react)
moduleResolution Strategy for resolving module (node or classic)

tsconfig.json Example

{
    
  "files": ["src/app/app.ts"],
  "compilerOptions": {
    
    "target": "es5",
    "removeComments": true,
    "alwaysStrict": true,
    "noEmitOnError": true,
    "noUnusedLocals": true,
    "noUnusedParameters": true
  }
}
  • alwaysStrict - ES 5 The code will execute in strict mode

  • noEmitOnError - When an error occurs , The compiler should not generate JavaScript Code

  • noUnusedLocals and noUnusedParameters - Indicates that the compiler will detect unused variables or parameters

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