当前位置:网站首页>Study notes for typescript

Study notes for typescript

2022-06-10 04:54:00 Minor dream

Lead to

  • nodejs Must install
  • Global installation typescript
npm install typescript -g
  • Use tsc Command to ts File for compilation
    • Enter named line
    • Get into ts File directory
    • Perform naming tsc xxx.ts that will do ,xxx.ts in xxx For the file name
      • If you do not compile without an error , By default, it will still be compiled , But it can be configured later without compiling
    • Compilation can be compiled to any js( Better compatibility ), You can configure it later through the configuration file

ts Basic type

  • The type declaration is TS A very important feature

  • Type declarations allow you to specify TS Medium variable ( Parameters 、 Shape parameter ) The type of

  • After specifying the type , When assigning a value to a variable ,TS The compiler will automatically check whether the value conforms to the type declaration , If yes, the value is assigned , Otherwise, the report will be wrong

  • In short , The type declaration sets the type... For the variable , So that variables can only store certain types of values

ts Some types

type Example describe
number1, -33, 2.5 Arbitrary number
string‘hi’, “hi”, hi Any string
booleantrue、false Boolean value true or false
Literal Its own The value of the limiting variable is the literal value
any* Any type
unknown* Type safe any
void Null value (undefined) No value ( or undefined)
never No value Cannot be any value
object{name:‘ The Monkey King ’} Any of the JS object
array[1,2,3] arbitrarily JS Array
tuple[4,5] Elements ,TS New type , Fixed length array
enumenum{A, B} enumeration ,TS New type in

Type declaration details

Type declaration ( Manual )

// Manually indicate the type 
let  Variable :  type ;

// Manually specify the type and assign a value 
let  Variable :  type  =  value ;

// Set the variable type and return value type of the function parameter 
function fn( Parameters :  type ,  Parameters :  type ):  type {
    
    ...
}

Type declaration ( Automatically )

  • Variables are declared and assigned at the same time ,ts Can automatically type detect variables
//ts Automatically indicates the type 
	// In this way, the variable type will be automatically judged according to the variable value 
let  Variable  =  A variable's value ;

Example

//  Variables are declared and assigned at the same time 
    // Indicates yes string type 
let typeString = '123';
typeString = "456";
// typeString = false;// Report errors 

Type declaration special case - Use the literal amount

  • Use literal to specify the type of variable , The value range of the variable can be determined by literal quantity
let zml:10;
zml = 10;
// zml = 100;// Report errors 

let sex: " male " | " Woman ";
sex = " male ";
sex = " Woman ";
// sex = " Unknown ";// Report errors 

let color: 'red' | 'blue' | 'black';
let num: 1 | 2 | 3 | 4 | 5;

ts Description of other types of

number

  • This is not a statement

  • Support hexadecimal representation

  • Sample code

let decimal: number = 6;
let hex: number = 0xf00d;
let binary: number = 0b1010;
let octal: number = 0o744;
let big: bigint = 100n;

boolean

  • Sample code
 let isDone: boolean = false;
 //let isDone: boolean = 134; Report errors 

string

  • Sample code

    let color: string = "blue";
    color = 'red';
     
    let fullName: string = `Bob Bobbington`;
    let age: number = 37;
    let sentence: string = `Hello, my name is ${
            fullName}. I'll be ${
            age + 1} years old next month.`;
    

any

  • Use any Any type , It is equivalent to turning off... For this variable ts Type detection of , And ordinary js The code is the same

    • Sample code ;
 // Specify the type when declaring , Explicit any 
let d: any = 4;
d = 'hello';
d = true;

// Variables are declared without specifying the type ts Automatically determine that the type of variable is any,, It is equivalent to declaring implicit any
let d; 

// The declaration shows ayn
let anyType:any;

let s:string = '123';
s = anyType;// There will be no error reporting , because d The type is any, Will harm others 

unknown

  • Sample code

    let notSure: unknown = 4;
    notSure = 'hello';
    
    let str:string = '123';
    // str = notSure;// An error has occurred ,unknown Will not harm others 
    

void

  • Indicates that there is no return value

  • Sample code

    let unusable: void = undefined;
    
    //void type 
    function fn1():void{
          
        console.log("123");
    }
    

never

  • Indicates that the result will never be returned , For example, this function is used to report errors , So never return results

  • Sample code

    function error(message: string): never {
          
      throw new Error(message);
    }
    

object

  • But this object Type is not used very often , Because in many cases object

  • such as typeof null The return value is object

  • also ts Think that a function is also a object

  • Sample code

    let obj: object = {
          };
    

{}

  • Used to specify which attributes can be included in an object , And the structure should be identical , More , No less !
  • such as let b: {name:string} // Set to point to an object , And there are name attribute , also name The attribute is string
  • Property name Add a question mark after it , Indicates that this attribute is optional
//sex Optional 
let myObj: {
     name: string, sex?: string };

myObj = {
     name: ' Li Bai ' };// Don't complain 
myObj = {
     name: ' Li Bai ', sex: ' male ' };// Don't complain 
  • [propName:string]:any Represents any type of attribute value ,propName The name can be anything , This is just to distinguish , It's fine too [xxxx:string]:any, Of course , If it is necessary to specify value The type of , You can put any Change to the specified type , such as [propName:string]:string Express value for string type

    // There must be key by name,value The type is string Value , And any number of others key( Type must be string) and value( The type is arbitrary )
    let myObj: {
           name: string, [propName: string]: any }
    myObj = {
           'name': ' Li Bai ', "sex": ' male ' };
    myObj = {
           'name': ' Li Bai ', "sex": ' male ', 'hobby': " having dinner " };// Don't complain 
    myObj = {
           'name': ' Li Bai ', "sex": ' male ', 'hobby': 555 };// Don't complain 
    

Set the type declaration of the function structure

  • grammar : ( Shape parameter 1: type 1 , Shape parameter 2: type 2 [,…] ) => Return value
  • such as hope getSum For the function , And there are two parameters , Are all number, And the return value is number
function getSum(a: number, b: number): number {
    return a + b;
}
  • hope getResult For the function , And there are two parameters , One for object, For another string, And the return value is number perhaps string
function getResult(a: object, b: string): number | string {
    
    return a + b;
}

array

  • Everything in the previous array can be saved , stay ts You can set the type of stored data

  • Format

    • type []
    • Array< type >
  • Sample code

    // Indicates that only... Can be stored in the array number type 
    let typeNumberArray:number[];
    let typeNumberArray:Array<number>;
    typeNumberArray = [1,2,3];
    // typeNumberArray = [1,2,'3'];// Report errors 
    
    
    let a:string[];// Represents an array of strings 
    let b:number[];// Represents an array of numbers 
    

tuple( Tuples )

  • Tuples are fixed length arrays , There are too many values stored in it , You can't go without it

  • What is not used with the type declaration of the array is the inversion , Now? [] It's in the front , The type is later

  • Sample code

    let x: [string, number];
    x = ["hello", 10]; 
    
    let h: [string, string];
    h = ['123', '456'];
    h = ['123'];// Less , Report errors ;
    h = ['123', '456', '689'];// More , Report errors 
    

enum( enumeration )

  • Sample code

    enum Sex {
          
        Male,
        Female
    }
    
    // Set the structure of an array to userName and sex
    let userInfo: {
           userName: string, sex: Sex };
    
    userInfo = {
          
        userName:" Li Bai ",
        // Use enumeration 
        sex:Sex.Male
    }
    
  • The above code is compiled js Code

var Sex;
(function (Sex) {
    
    Sex[Sex["Male"] = 0] = "Male";
    Sex[Sex["Female"] = 1] = "Female";
})(Sex || (Sex = {
    }));
// Set the structure of an array to userName and sex
var userInfo;
userInfo = {
    
    userName: " Li Bai ",
    // Use enumeration 
    sex: Sex.Male
};

&( It means that the conditions are met at the same time )

// Express key There must be name Properties and age attribute , And conform to the regulations value type 
let all: {
     name: string } & {
     age: number };
all = {
    
    name: " Li Bai ",
    age: 1000
}

type( Type the alias )

  • Keywords are type
type myType = 1 | 2 | 3 | 4 | 5 | 6;
let one: myType;
let two: myType;
let three: myType;
let four: myType;

Types of assertions

  • Sometimes the binary type compiler judges differently , But we already know that the two sides are of the same type , At this point, you can use type assertions

  • grammar Variable as type perhaps < type > Variable

  • such as : If you will unknown Assign values to other types of variables , An error will be reported , So we need type assertions

    let notSure: unknown = 'biubiu';
    
    let strType = '123';
    
    // No assertion , Will report a mistake 
    // strType = notSure;
    
    // Make type assertions 
    strType = notSure as string;
    // Or this form of type assertion 
    
    strType = <string> notSure;
    

ts compile

Automatic compilation ( Single file compilation , No configuration files are required )

  • When compiling files , Use -w After the instruction ,ts The compiler will automatically monitor the changes of the file , And recompile the file when it changes
  • Example : tsc xxx.ts -w
  • shortcoming : Only one file can be ts, Because there is no configuration file !

Automatic compilation ( The whole compilation , There are configuration files )

  • Profile name is tsconfig.json

  • tsconfig.json It's a JSON file , Fill in the configuration file

  • Be careful : tsconfig.json You can add comments ~ Other JSON No

  • tsconfig.json Configuration object as follows , Official website API

1.include

  • Set the directory where you want the files to be compiled , Is an array
  • The default value is : ["**/*"] Represents all folders and files under the current named line

Example :

{
    
    //  all src Contents and tests The files and folders in the directory ts file , Will be compiled 
    "include": ["src/**/*", "tests/**/*"],
}

Get to know ** and * stay tsconfig.json The role of

  • **/ Recursively match any subdirectory
  • * Indicates matching any file

2.exclude

  • Set exclusion list
  • The default value is :["node_modules", "bower_components", "jspm_packages"]

Example :

{
    
    // test Contents and lower level, etc ts Files will not compile 
    "exclude": ["./test/**/*"],
}

3.files

  • Specify the list of compiled files , It is only used when there are few files to compile

Example : All files in the list will be ts The compiler compiles

{
    
  "files": [
    "core.ts",
    "sys.ts",
    "types.ts",
    "scanner.ts",
    "parser.ts",
    "utilities.ts",
    "binder.ts",
    "checker.ts",
    "tsc.ts"
  ]
}

4.extends

Example :

{
    
    // In the above example , The current configuration file will be automatically packaged to contain config In the catalog base.json All the information in the file 
	"extends":"./config/base",
}

5.compilerOptions( important )

  • Compiler options , For example, compile mode , It's made up of key and value Composed of
  • The following are common key
1.taget
  • Used to indicate ts Compiled into js Version of , The default value is "es3"
  • Optional value is : 'es3', 'es5', 'es6', 'es2015', 'es2016', 'es2017', 'es2018', 'es2019', 'es2020', 'es2021', 'esnext'.

target Set to es6 The effect of

// Before Compilation  // After compiling 
var a = 123;           =>  var a = 123;
var b = 'true';        =>  var b = 'true';
let c = ' I am a dynamic Superman ';  =>  let c = ' I am a dynamic Superman ';
console.log(c);        =>  console.log(c);
setTimeout(()=>{
    	   => {
    setTimeout(function () {
    
    
}, 900);				}, 900);
2.module
  • Indicate the modular specification to use
  • Optional value is :'none', 'commonjs', 'amd', 'system', 'umd', 'es6', 'es2015', 'es2020', 'es2022', 'esnext', 'node12', 'nodenext'

Examples are shown in the figure : Set the modular specification to commonjs

index.ts Use es6 Modular specification export say function ,app.ts introduce say Function and output , Then view the compiled app.js

3.outDir
  • Specifies the compiled js File directory
  • By default , The compiled js The document will be with ts The files are located in the same directory , Set up outDir After, you can change the location of the compiled file

Example :

{
    
    "compilerOptions": {
    
        //  Will be compiled js The file is output to... In the directory where the current configuration file is located dist Under the folder 
        "outDir": "./dist",
    }
}
4.outFile
  • Compile all the files into one js file , By default, all will be written in Code under global scope Merge into one js file
  • If module The configuration item specifies none,style perhaps amd, Then the modules will be merged into the file , Only these can ,es6 Can not be
5.lib
  • Indicate the library to use
  • Values that can be written
'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'es2018', 'es2019', 'es2020', 'es2021', 'esnext', 'dom', 'dom.iterable', 'webworker', 'webworker.importscripts', 'webworker.iterable', 'scripthost', 'es2015.core', 'es2015.collection', 'es2015.generator', 'es2015.iterable', 'es2015.promise', 'es2015.proxy', 'es2015.reflect', 'es2015.symbol', 'es2015.symbol.wellknown', 'es2016.array.include', 'es2017.object', 'es2017.sharedmemory', 'es2017.string', 'es2017.intl', 'es2017.typedarrays', 'es2018.asyncgenerator', 'es2018.asynciterable', 'es2018.intl', 'es2018.promise', 'es2018.regexp', 'es2019.array', 'es2019.object', 'es2019.string', 'es2019.symbol', 'es2020.bigint', 'es2020.promise', 'es2020.sharedmemory', 'es2020.string', 'es2020.symbol.wellknown', 'es2020.intl', 'es2021.promise', 'es2021.string', 'es2021.weakref', 'es2021.intl', 'esnext.array', 'esnext.symbol', 'esnext.asynciterable', 'esnext.intl', 'esnext.bigint', 'esnext.string', 'esnext.promise', 'esnext.weakref'.
6.allowJs
  • Whether the js File for compilation , Because the current directory will have more than ts, There may be js file
  • The default is false, On behalf of not compiling js
  • by true For compiling , by false On behalf of not compiling js
7.checkJs
  • Whether the js Check the documents
  • The default is false, They don't check
8.removeComments
  • Remove comments
  • The default is false Means not to remove
9.noEmit
  • Do not generate compiled files
  • The default is false, Represents the generation of compiled files
  • It is generally used when you only want to use ts Use this configuration item for syntax checking
10.noEmitOnError
  • When there is an error, the compiled file is not generated
  • The default is false, representative ts If an error is reported in the file, it will be generated js file , So we can often see that an error is reported and the compiler generates js The file is for this reason

Strictly check the series

11.strict( Main switch )
  • Opened this , All the following configuration items will be set to true, The default value is false
12.alwaysStrict
  • Always compile code in strict mode

  • Be careful : If used es6 modularization , Then the strict mode is automatically turned on , Therefore, it will not be added after compilation "use strict" keyword

  • The value can be true | false

13.noImplicitAny
  • Prohibit implicit any type , The default is false
  • Set to true after , implicit any Type not allowed

14.noImplicitThis
  • Prohibit ambiguous types of this

Pictured So point out this The type of Tested . Assertions are not allowed to ignore this statement

Ignore mistakes

  • For example, according to id obtain , May not be available , But it has been confirmed Add one at the end !
    • var a = document.getElementById(“food”)!;
  • @ts-ignore Ignore current line errors

ts-node( Compile operation ts Code )

install :

npm install ts-node -g

Use : xxx.ts Is the file name

ts-node xxx.ts

class class

  • In fact, some of our thoughts have already existed , such as
    • To operate the browser, use window object
    • To operate a web page, use document object
    • The operation console shall use console object
  • ts Classes exist as a type

Pictured , Demonstrated a Person type , A kind of string type

 Pictured , Demonstrated a Person type , A kind of string type

Instance properties of class

  • Instance attributes , Is the property of the instantiated object , The instance properties in each instance object are independent
  • When declaring instance properties , You can assign an initial value , It can also be passed later constructor Function to assign an initial value
class Person {
    
    age: number;
    sex: string;
    gender = ' male ';
}

Class constructor

  • Constructors , Is a function that assigns an initial value to an instance property !
  • Be careful , The return value and return value type are not required in the constructor !
  • Be careful , If not in constructor The instance attribute is indicated above , You may not be prompted when entering the code

Correct ( Contains instance properties )

class Person {
    
    age: number;
    sex: string;
    constructor(age, sex) {
    
        this.age = age;
        this.sex = sex;
    }
}
var p1 = new Person(100,' male ');
console.log(p1.age);

FALSE , Instance properties are not declared

class Person {
    
    // age: number;
    // sex: string;
    constructor(age, sex) {
    
        this.age = age;
        this.sex = sex;
    }
}
var p1 = new Person(100,' male ');
console.log(p1.age);

There is no error prompt for declaring instance properties

 There is no error prompt for declaring instance properties

Class inheritance

extends(js,ts There are )

  • Not much to say , Look at the code ~ keyword extends, Remember to call super To call the constructor of the parent class
// Parent class 
class Animal {
    
    name: string;
    food: string;
    // Call 
    ww: string;
    constructor(name: string, food: string, ww: string) {
    
        this.food = food;
        this.name = name;
        this.ww = ww;
    }
    say() {
    
        console.log(` I will ${
      this.ww} It's called `);
    }
}

// Subclass  -  Inherit  Animal class 
class Dog extends Animal {
    
    constructor(name: string, food: string, ww: string) {
    
        super(name, food, ww);
    }
}
var xiaobai = new Dog(" The small white ", " Dog food ", " Wang Wang ");
console.log(xiaobai);

Visibility modifier ( Used for properties or methods )

public

  • public : The default value is , All members can access... From anywhere , Whether it is a subclass after inheritance , Or myself , Fine
  • If the visibility modifier is not specified, it defaults to public

protected

  • Protect : Can only be used in the classes and subclasses in which it is declared ( Instantiated object not available )

Sample code : Set the call to private property

// Parent class 
class Animal {
    
    name: string;
    food: string;
    // Call 
    protected ww: string;// Set as private property 
    constructor(name: string, food: string, ww: string) {
    
        this.food = food;
        this.name = name;
        this.ww = ww;
    }
    say() {
    
        console.log(` I will ${
      this.ww} It's called `);
    }
}

// Subclass  -  Inherit  Animal class 
class Dog extends Animal {
    
    constructor(name: string, food: string, ww: string) {
    
        super(name, food, ww);
    }
}
var xiaobai = new Dog(" The small white ", " Dog food ", " Wang Wang ");

// Report errors 
// Tips : attribute “ww” The protected , Only in class “Animal” And its subclasses 
console.log(xiaobai.ww);

Wrong presentation

 Wrong presentation

Modifier for method

 Modifier for method

private

  • private : Can only be used in the class in which it is declared , Nothing else can be used

Sample code

class Person{
    
    private name: string;
    private age: number;

    constructor(name: string, age: number){
    
        this.name = name; //  You can modify 
        this.age = age;
    }

    sayHello(){
    
        console.log(` Hello everyone , I am a ${
      this.name}`);
    }
}

class Employee extends Person{
    

    constructor(name: string, age: number){
    
        super(name, age);
        this.name = name; // Cannot modify in subclass 
    }
}

const p = new Person(' The Monkey King ', 18);
p.name = ' Pig eight quit ';//  Do not modify 

readonly Modifier ( Only available for attributes )

  • readonly Indicates read-only , be used for Prevent attribute base assignment outside the constructor !!!

  • Use readonly Keyword modifies that the attribute is read-only , Note that you can only modify attributes, not methods .

  • Interface or {} Represents the object type , You can also use readonly

  • As long as it is readonly To modify the properties of , Explicit types must be provided manually , Otherwise, it becomes a literal quantity !

Sample code :

class Person {
    
    // As long as it is readonly To modify the properties of , Explicit types must be provided manually , Otherwise, it becomes a literal quantity !
    readonly age: number = 18;
    constructor(age: number) {
    
        this.age = age;
    }
}

var p1 = new Person(100);
console.log(p1);
// Report errors , Prompt cannot be assigned to  "age" , Because it's a read-only property 
p1.age = 200;

Sample code : be used for {}

let obj: {
     readonly name: string } = {
     name: 'jack' };
// Report errors , Prompt cannot be assigned to  "name" , Because it's a read-only property .
obj.name = 'Mike';

Interface (interface)

  • Interfaces act like abstract classes , The difference is All methods and properties in the interface have no real values , In other words, all methods in the interface are abstract methods . Interface is mainly responsible for defining the structure of a class , Interface can be used to restrict the interface of an object , An object can match an interface only if it contains all the properties and methods defined in the interface . meanwhile , You can let a class implement the interface , When implementing the interface, all properties in the interface should be protected in the class .
  • You can use interfaces to constrain objects
  • You can also use interfaces to constrain classes

Example : Use interfaces to constrain objects

interface Person {
    
    name: string;
    // It is specified that there should be a function as 'sayHello', And no value is returned 
    sayHello(): void;
}

// Stipulate this per The object structure of is Person Structure defined 
function fn1(per: Person) {
    
    // call per In the middle of sayHello
    per.sayHello();
}
var myObj = {
    
    name: " The Monkey King ",
    //es6 Writing 
    // sayHello(){
    
    // console.log(" Call me Qi Tian Da Sheng !");
    // }
    // Or this es5 The way of writing is also OK 
    sayHello: function () {
    
        console.log(" Call me Qi Tian Da Sheng !");
    }
}

fn1(myObj);

Example : Use interfaces to constrain classes

interface Person {
    
    name: string;
    sayHello(): void;
}

class Student implements Person {
    
    constructor(public name: string) {
    
    }

    sayHello() {
    
        console.log(' Hello everyone , I am a ' + this.name);
    }
}

abstract class / Abstract method

  • Abstract classes are classes that are specifically used to be inherited by other classes , It can only be inherited by other classes and cannot be used to create instances
  • Abstract classes can have Abstract method and Common method
  • Abstract methods can only be defined in abstract classes
  • Subclass It has to be Rewrite abstract methods of abstract classes

Example

abstract class Animals {
    
    // Define abstract methods 
    abstract run(): void;
    say() {
    
        console.log(" Animals are barking ");
    }
}
class Dog extends Animals {
    
    run() {
    
        console.log(" Dogs bark ");
    }
}

var xiaobai = new Dog();
xiaobai.run();// Output : Dogs bark 
xiaobai.say();// Output : Animals are barking 

Generic (Generic)

  • When defining a function or class , In some cases, it is not possible to determine the specific type to be used ( Return value 、 Parameters 、 The type of the property cannot be determined ), At this point, generics can work .

  • Format , Add... Before parentheses <>

  • Like a function , I require a parameter , The type of the parameter passed in by the user is the type of the return value of the function , How to do that ? Use generics

It is not recommended to use any!

//! It is not recommended to use any!
function test(arg: any): any{
    
	return arg;
}

Use generics

  • there <T> It's generic ,T We named this type ( Not necessarily T), Once the generics are set, they can be used in functions T To represent the type . So generics are actually easy to understand , It means a certain type .
function test<T>(arg: T) {
    
    return arg;
}

So how to use generic defined functions ?

  • Mode one : Use it directly
  • When in use, you can directly pass parameters , The type will be determined by TS Automatically infer , But sometimes when the compiler cannot automatically infer, you need to use the following method
function test<T>(arg: T) {
    
    return arg;
}

// Mode one ( Use it directly ):
console.log(test(" Li Bai "));// Output : Li Bai 
console.log(test(123));// Output :123


  • Mode two : Indicate the type
function test<T>(arg: T) {
    
    return arg;
}

//  Mode two : Indicate the type 
console.log(test<string>(' Du Fu '));// Output : Du Fu 
console.log(test<boolean>(true));// Output :true
  • Multiple generics can be specified at the same time , Generics are separated by commas :
function test2<T, K>(arg1: T, arg2: K): K {
    
    return arg2;
}

test2<number, string>(100, ' Du Fu ');
  • Generics can also be used in classes :
class MyClass<T>{
    
    prop: T;

    constructor(prop: T){
    
        this.prop = prop;
    }
}
  • besides , You can also constrain the scope of generics

Use T extends MyInter For generics T Must be MyInter Subclasses of , You don't have to use interface classes. The same applies to abstract classes .

interface MyInter{
    
    length: number;
}

function test<T extends MyInter>(arg: T): number{
    
    return arg.length;
}
原网站

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