• Recommendation: Learn TypeScript early to compete in the workplace

Source: making stars ✨ | o | give a ❤ ️ attention, ❤ ️ thumb up, ❤ ️ encourages the author

I hope I can help more friends. Add me 😚 can exchange problems (not big guy, learn from each other, create a good learning environment). Which of the following do you not understand?

Open in another page to hd

TypeScript development

Install typescript globally, using the install command either using NPM or yarn:

npm install typescript -g

yarn global add typescript
Copy the code

demo.ts

function jeskson() {
 let web: string = "hello world"
 console.log(web)
}

jeskson()

// tsc
tes demo.ts
node demo.js
Copy the code

npm install -g ts-node
Copy the code

The data type

  • Data type of TS
/ / ES6 data types: basic data types: Boolean, Number, String, Symbol, undefined, null reference type: Array,Function,Object // TS data types, void,any,never, tuple, enumeration, advanced typesCopy the code

Type comments:

let hello : string = 'Hello TypeScript'
Copy the code

The original type

let bl: boolean = true
let num: number = 123
let str: string = "123"
Copy the code

An array of generics

let arrType: Array<number> = [0, 1, 2, 3, 5];
let arrType1: Array<string> = ['0', '1', '2', '3', '5'];
let arrType2: Array<any> = [1, '1', 2, 's', true];
Copy the code

Represent arrays with interfaces

interface Person{ name: string; age: number; } interface NumberArray { [index:number]: Person; } let arrType4: Array<Person> = [{name:' Person ', age: 20}] let arrType4: Array<Person> = [{name:' Person ', age: 20] 20}] let arrType5: Person[] = [{name:' zhang ', age: 20}]Copy the code

An array of class

Array-like Object is not an Array type:

function sum() {
    let args: number[] = arguments;
}

// index.ts(2,7): error TS2322: Type 'IArguments' is not assignable to type 'number[]'.
//   Property 'push' is missing in type 'IArguments'.

function sum() {
    let args: IArguments = arguments;
}
Copy the code

A tuple type

Let tuple: [number, string] = [0, '1'] let tuple: [number, string] = [0, '1'] let tuple: [number, string] = [0, '1']Copy the code

function

Function declarations and Function expressions

Function Declaration Function sum(x, y) {return x + y; } // let mySum = Function (x, y) {return x + y; };Copy the code
Function sum(x:number,y:number):number{return x+y} Let mySun = function(x:number,y:number):number{return x + y}Copy the code

Define the shape of a function with an interface

Interface SearchFunc {(source: string, the subString: string) : Boolean} let mySearch: SearchFunc; mySearch = function(source: string,subString:string){ return source.search(subString) ! = = 1}Copy the code

Similar to optional attributes in interfaces, we use? Represents optional parameters:

function buildName(firstName: string, lastName? : string) { if (lastName) { return firstName + ' ' + lastName; } else { return firstName; } } let tomcat = buildName('dada', 'Cat'); let tom = buildName('dada');Copy the code

Parameter Default Value

function buildName(firstName:string,lastName:string='Cat'){
    return firstName + ' ' + lastName;
}
let tomcat = buildName('dada', 'Cat');
let tom = buildName('dada');
Copy the code

The remaining parameters

// You can use... Function push(array,... Item){item.foreach (function(item){array.push(item)})} let a = []; Push (a, 1, 2, 3) the function of push (array: any [],... items:any[]){ items.forEach(function(item){ array.push(item); } let a = [] push(a,1,2,3)Copy the code

overloading

Overloading allows a function to take different numbers or types of arguments and behave differently

function reverse(x: number | string): number | string { if (typeof x === 'number') { return Number(x.toString().split('').reverse().join('')); } else if (typeof x === 'string') { return x.split('').reverse().join(''); }}Copy the code

Use overloading to define multiple reverse function types:

function reverse(x: number): number; function reverse(x: string): string; function reverse(x: number | string): number | string { if (typeof x === 'number') { return Number(x.toString().split('').reverse().join('')); } else if (typeof x === 'string') { return x.split('').reverse().join(''); }}Copy the code

The static type

let count : number = 1;

interface dada {
 uname: string,
 age: number
}

const jeskson :dada = {
 uname: 'jeskson',
 age: 12
}
Copy the code

Object type:

const gege: {
 name: string,
 age: number
} = {
 name: 'jeskson',
 age: 12
}
Copy the code
Const person: string [] = ['dada', 'Jeskson ',' Nezha ']Copy the code
class Person{}
const dada : Person = new Person()

const dada :()=>string = ()=>{return 'jeskson'}
Copy the code

Static types: object types, array types, class types, function types

Type annotations and type inference

Local variables:

let count : number;
count=12;
Copy the code

Not if TS can automatically analyze variable types, otherwise type annotations are required.

Annotation of function parameters and function return types

Function getNum(a: number, two: number) : number {return a + b} const total = getNum(1,2)Copy the code

never

function errorFunction() : never {
 throw new Error()
 console.log('hello world')
}

function forNever() : never {
 while(true) {}
 console.log('hello world')
}

function add({one,two} : {one : number,two : number}) {
 return one + two
}
const total = add({one:1,two:2})
Copy the code

Array type annotation

Const numberArr: number[] = [1,2,3] const string: string[] = ['a','b','c'] const undefinedArr: undefined[] = [undefined, undefined] const arr : (number | string)[] = [1,'string',2] const dada : {name: string, age: number} [] = [{name: 'jeskson, age: 12}, {name:' Lord which zha, age: 12}, ] // Type alias Type typeMy = {name:string,age:number} const dada: typeMy[] = [{name:'jeskson',age:12}]Copy the code

tuples

Strengthen the version:

Const dada: (string | number) [] = [' Lord which zha ', 'jeskson, 12] / / not commonly used - tuple const dada1: [string,string,number] = ["jeskson",12,"dadaqianduan"]Copy the code

interface

interface dada { name: 'jeskson'; age: 12; work ? : string; say():string; } class obj implements dada { name="dada" age=12 work="it" say(){ return "dadaqianduan" } } const selected = (person: dada)=>{ } // obj.name && console.log(obj.name)Copy the code

class

SayHello () {return this.content}} consot Da = new Da() console.log(da.sayHello())Copy the code
class Person {
 name: string;
}
const person = new Person()
person.name = "jeskson"
console.log(person.name)
Copy the code

Class constructor

class Person { public name : string; Constructor (public name:string){this.name = name}} class Person {constructor(public name:string){}} class Teacher extends Person{ constructor(public age:number){ super('jeskson') } } const person = new Person('jeskson') const dada = new Teacher(12) console.log(dada.age) console.log(person.name)Copy the code

Getter,Setter,static

class Da {
 constructor(private _age:number){}
 get age() {
  return this._age
 }
 set age(age:number) {
  this._age = age
 }
}

const dada = new Da(12)
Copy the code
Static sayHello() {return console.log(da.sayHello ())Copy the code

Read-only properties:

class Person{
 public readonly _name:string
 constructor(name:string) {
  this._name = name
 }
}
const person = new Person('jeskson');
console.log(person.name);
Copy the code

Abstract classes, using inherited abstract classes:

abstract class Da {
 abstract say()
}
class da extends Da {
 say() {
  console.log('jeskson')
 }
}
Copy the code

Tsc-init generates tsconfig.json file:

CompilerOptions configuration items

"Files ": [] removeComments is true, strict is true, write specification // Allow your annotation type any not to specify "noImplicitAny": StrictNullChecks: true // entry file "rootDir": "./ SRC "// compiled file "outDir": "./build" // Generates corresponding '.map' file true // Report errors on unused locals "noUnusedLocals": trueCopy the code

Federated type and type protection

interface Teacher{ teacher: boolean; say:()=>{} } interface Student{ teacher: boolean; Say: () = > {}} / / joint type, the type of protection, type of assertion function da (study: the Teacher | Student) {if (study. The Teacher) {(study as the Teacher.) say (); }else{ (study as Student).say(); }}Copy the code

The generic

function fn<T>(params: Array<T>){
 return params;
}
fn<string>(["12","123"]);
Copy the code

Use:

class Select {
 constructor(private da: string[]) {}
 getDa(index:number):string{
  return this.da[index];
 }
}
const dada = new Select(["1","2","3"]);
onsole.log(dada.getDa(1));
Copy the code
class Select<T> { constructor(private da: T[]){} getDa(index: number): T{ return this.da[index]; }}Copy the code
interface Girl { name: string; } class SelectGirl<T extends Girl> { constructor(private girls: T[]) {} getGirl(index: number): string { return this.girls[index].name; } } class SelectGirl<T extends number | string> { constructor(private girls: T[]) {} getGirl(index: number): T { return this.girls[index]; }}Copy the code

NameSpace

NPM init-y generates package.json file

Tsc-init generates the tsconfig.json file

Install the VsCode editor:

interface Person {
 name: string
}
const teacher: Person = {
 name: 'jeskson'
}
Copy the code

Base type and object type

// Base type null, undefined, symbol, Boolean, void const count:number = 12; Const name:string = 'Nezha '; // Object type const teacher: {name: string; age: number; } = { name: 'jeskson', age: 12 }; Const nums:number[] = [1,2,3] const goTotal: ()=>number = ()=> {return 123; }Copy the code

Type annotations and type inference

// type annotation let count:number; count=123; // Type inference, TS will automatically try to analyze the type of variablesCopy the code
Function getTotal(firstNumber:number, secondNumber:number) {return firstNumber + secondNumber; } const total = getTotal(1,2);Copy the code

Function dependent type

Function getTotal(firstNumber:number, secondNumber:number):number {return firstNumber + secondNumber; } const total = getTotal(1,2); Function sayHello(): void {console.log('hello'); Function errobocketter (): never {while(true){} //Copy the code
function add({first,second}:{first:number; second:number}):number{ return first+second; } function getNumber({first}:{first:number}){ return first; }Copy the code

Summary:

/ / the base type Boolean, number, string, void, undefined, symbol, null let count: number; count = 12; // Object type {},Class,function,[] const fun = (STR :string) => {return parseInt(STR,10); } const fun1: (str:string)=>number = (str) => { return parseInt(str,10); } const date = new Date();Copy the code

Arrays and tuples

const arr: (number|string)[] = [1,'2',3]; const stringArr: string[] = ['a','b','c']; const undefinedArr:undefined[] = [undefined]; Const objectArr: {name:string,age:number}[] = [{name: 'Nezha ', age: 12}] // type alias alias type User = {name:string; age:number}; Const objectArr: User[] = [{name: 'nezha ', age: 12}] class Teacher {name: string; age: number; } const objectArr: Teacher[] = [ new Teacher(); { name: 'jeskson', age: 12 } ];Copy the code

tuples

const teacherInfo: [string, string, number] = ['dadaqianduan','1024bibi.com',12];
Copy the code

Interface Interface

interface Person { // readonly name: string; name: string; age? : number; } const getPersonName = (person: Person): void => { console.log(person.name); }; const setPersonName = (person: Person, name: string): void=>{ persono.name = name; }; Const person = {name: 'Nezha ', age: 12}; getPersonName(person);Copy the code

Class definition and inheritance

Class Person {name=' Nezha '; getName() { return this.name; } } class Teacher textends Person { getTeacherName() { return 'teacher'; } getName() { return '1024bibi.com' + super.getName() } } const teacher = new Teacher(); // overwrite, word classes can overwrite things from their parent classesCopy the code

Class access types and constructors

// private protected public class Person { public name: string; sayHi() { console.log('1024bibi.com') } } const person = new Person(); Person. name = 'console.log' (person.name); // public allows me to be called inside and outside a class. // private allows me to be used inside a class. // Protected allows me to be used inside a class and in an inherited subclassCopy the code
  • constructor
class Person {
 public name: string;
 constructor(name: string) {
  this.name = name;
 }
}

const person = new Person('dadaqianduan');
console.log(person.name);
Copy the code
Class Person {constructor(public name: string) {}}Copy the code
class Teacher extends Person { constructor(public age:number) { super('dadaqianduan'); }} // Empty super() is also used if the parent class has no constructorCopy the code

Static properties, setters and getters

class Person {
 constructor(private name: string) {}
 get getName() {
  return this.name;
 }
}

const person = new Person('dadaqianduan');
console.log(person.getName);
Copy the code
class Person { constructor(private _name: string) {} get name() { return this._name; } set name(name: string) { this._name = name; }}Copy the code

Design pattern: singleton pattern, a class is allowed to obtain only one singleton instance from this class

class Demo { private static instance: Demo; private constructor(public name:string) {} static getInstance(name: string) { if(! this.instance) { this.instance = new Demo('1024bibi.com'); } return this.instance; } } //const demo1 = new Demo(); //const demo2 = new Demo(); const demo1 = Demo.getInstance();Copy the code

An abstract class

Abstract classes can only be inherited, not instantiated

abstract class Da {
 width: number;
 getType() {
  return 'dadaqianduan';
 }
 abstract getAra(): number;
}
Copy the code
npm init -y
Copy the code

Generate package.json file:

{" name ":" TypeScript ", "version" : "1.0.0", "description" : ""," main ":" index. Js ", "scripts" : {" test: echo \ "" Error: no test specified\" && exit 1" }, "keywords": [], "author": "", "license": "ISC" }Copy the code
tsc --init
// Successfully created a tsconfig.json file

// npm uninstall ts-node -g
Copy the code
npm install -D ts-node
Copy the code
npm install typescript -D
Copy the code

Configuration files in TypeScript

Json File to compile "include" ["./demo.ts"],Copy the code

Federated type and type protection

interface Bird { fly: boolean; sing: ()=>{}; } interface Dog { fly: boolean; bark: ()=>{}; } / / type assertion function trainAnial (animal, Bird | Dog) {if (animal. Fly) {(animal as Bird.) sing (); } else { (animal as Dog).bark(); }} / / grammar to do type protection function in trainAnialSecond (animal, Bird | Dog) {if (' sing 'in animal) {animal. Sing (); } else { animal.bark(); }}Copy the code
/ / typeof grammar type protection function to do the add (first: string | number, the second: string | number) { if(typeof first === 'string' || typeof second === 'string') { return `${first}${second}`; } return first + second; } // Use instanceof syntax for type protection class NumberObj {count: number; } function addSecond(first: object | NumberObj, second: object | NumberObj) { if(first instanceof NumberObj && second instanceof NumberObj) { return first.count + second.count;  } return 0; }Copy the code

Enum Enum type

const Status = {
 OFFLINE: 0,
 ONLINE: 1,
 DELETED: 2
}
function getResult(status) {
 if(status === Status.OFFLINE){
  return 'offline';
 }else if(status === Status.ONLINE) {
  return 'online';
 }else if(status === Status.DELETED) {
  return 'deleted';
 }
 return 'error';
}
Copy the code
enum Status {
 OFFLINE,
 ONLINE,
 DELETED2
}
function getResult(status) {
 if(status === Status.OFFLINE){
  return 'offline';
 }else if(status === Status.ONLINE) {
  return 'online';
 }else if(status === Status.DELETED) {
  return 'deleted';
 }
 return 'error';
}
Copy the code

The function of generic

Function join<T,P>(first: T, second: P) {return '${first}${second}'; } function anotherJoin<T>(first: T,second: T): T { return first; } // T[] function map<T>(params: Array<T>) { return params; } // join<number,string>(1,'1'); // map<string>(['123']); join(1,'1');Copy the code

How are generics used in classes

interface Item { name: string; } class DataManager<T extends Item> { constructor(private data: T[]) {} getItem(index: number):string { return this.data[index].name; } } const data = new DataManager({ { name: 'jeskson' } ]}; // How to use generics as a concrete type annotation function hello<T>(params: T) {return params; } const func: <T>(param: T) => T = hello;Copy the code

The namespace

"use strict" var Header = (function() { function Header() { var elem = document.createElement('div'); elem.innerText = 'This is Header'; document.body.appendChild(elem); } return Header; } ()); var Content = (function()=>{ function Content() { var elem = document.createElement('div'); elem.innerText = 'This is Content'; document.body.appendChild(elem); } return Content }());Copy the code

Use Parcel to package TS code

yarn add --dev parcel@next
Copy the code

The use of keyof syntax in generics

An array collection of keys of a data type that applies to both arrays and objects

interface testInter { name: string, age: number } let testArr: string[] = ['dada', 'dada1']; Let testObj: testInter = {name: 'Tate ', age: 26} function extends keyof T, T> Array<string>) { return key; } showKey<number, Array<string>>(1, testArr); Function extends keyof T> (keyItem: K, obj: T): K {return keyItem; } let val = showKey('name', testObj) function showKey<K extends keyof T, T> (items: K[], obj: T): T[K][] { return items.map(item => obj[item]) }Copy the code
interface Person {
 name: string;
 age: number;
 gender: string;
}
class Teacher {
 constructor(private info: Person) {}
 getInfo(key: string) {
  if(key==='name' || key==='age' || key==='gender') {
   return this.info[key];
  }
 }
}
 
const teacher = new Teacher({
 name: 'jeskson',
 age: 12,
 gender: 'male'
});
const test = teacher.genInfo('name');
Copy the code
class Teacher { constructor(private info: Person) {} // getInfo<T extends keyof Person>(key:string) { getInfo<T extends keyof Person>(key: T):Person[T]{ return this.info[key]; }}Copy the code

A decorator

// Class decorator // Decorator itself is a function // Decorator is used through the @ symbolCopy the code
// Target corresponds to the prototype static method, Function getNameDecorator(target:any,key:string){console.log(target,key); } class Test { name: string; constructor(name: string){ this.name = name; } @getNameDecorator static getName() { return '123'; }}Copy the code

Interface Interface

Sometimes we pass in a parameter that contains many attributes, but the compiler only checks that the required attributes exist and that the types match, and interfaces are used to describe such structures.

function Person(config: {name:string,age:number}) { console.log(config.name+config.age); } console.log(Person({name:' Nezha ',age:12})); Interface Config {name: string; age: number; } function Person(config: Config) { console.log(config.name+config.age); } // Interface type checking checks whether attributes are restricted in the Config interfaceCopy the code

Optional attribute

Attributes in an interface are sometimes unnecessary and optional in cases where they are useful or not, so that possible attributes are defined in advance.

interface Config { name: string; age? : number; // [propName: string]: any to string index signature} // [propName: string]: Any // This index signature is used to protect against errors in // property names that you can anticipate that an object may be used for a particular purposeCopy the code

Read-only property

For some object attributes that can only be modified when the object is created, use readonly before the attribute to specify read-only attributes:

interface Point { readonly x: number; readonly y: number; } let p:Point = {x: 12, y: 14} p.x = 15Copy the code

Function types

Interfaces can describe the various shapes that objects in JavaScript can have

Function type interface:

interface Fun {
 (source: string, subString: string): Boolean
}
Copy the code

Interface inheritance

Interfaces can inherit from each other, and can copy members from one interface to another.

interface Animal {
 name: string;
 say(): void;
}
interface Person extends Animal {
 work(): void;
 closer: string;
}
class Pro implements Person {
 closer: string;
 name: string;
 say(): void {
 
 }
 work(): void {
 
 }
 constructor(name:string, closer:string) {
  this.name = name;
  this.closer = closer;
 }
}
let g:Person = new Pro("jeskson","it");
g.say();
g.work();
Copy the code
  • Object type interface
  • Function type interface

How to define an interface: use the interface keyword

The interface can be defined as:

  • Determine the attribute
  • Optional attribute
  • Any attribute
  • Read-only property
  1. Determine the attribute
interface UserInfo {
 name: string;
 age: number;
}

const myInfo: UserInfo = {
 name: '魔王哪吒',
 age: 12
}
Copy the code

Interface constraints good deterministic attributes, defining object variables, no less, no more 🙅

  1. Optional attribute
interface UserInfo { name: string; age: number; sex? : string; } const myInfo: UserInfo = {name: 'Nezha ', age: 12}Copy the code

An optional attribute in an interface indicates that it may not exist in an object variable

  1. Any attribute
interface UserInfo { name: string; age: number; sex? : string; [proName: string]: any; } const myInfo: UserInfo = { name: "dadaqianduan", age: 12, test1: '123', test2: 'abc', test3: 123 };Copy the code

Once any attribute is defined, the types of both the determined attribute and the optional attribute must be subclasses of any attribute type. After any attribute is defined, the number of attributes in an object variable can be greater than the number of attributes in the interface.

  1. Read-only property
interface UserInfo { readonly id: number; name: string; age: number; sex? : string; [propName: string]: any; }Copy the code
const myInfo: UserInfo = {
  id: 1,
  name: "dada",
  age: 12,
  test1: "123",
  test2: "abc",
  test3: 123
};
Copy the code

Read-only attributes, which are also deterministic attributes, must have a value when an object variable is defined and cannot be changed later

  • Object interface to query a list of goods
interface ResponseData { resCode: number; resData: ResultData[]; message: string; } interface ResultData { productId: number; productName: string; } let resultData = {resCode: 0, resData: [{productId: 1, productName:"TypeScipt actual "}, {productId: 2, productName:"TypeScipt from start to finish "},], message: "success"} function render(res: ResponseData) { console.log(res.resCode, res.message) res.resData.forEach((obj) => { console.log(obj.productId, obj.productName) }) } render(resultData);Copy the code

As long as the object passed in meets the necessary conditions of the interface, it is allowed, and even the passing of extra fields can pass type checking

  • There are three ways to bypass the check:
  1. Assigns an object literal to a variable
Let result = {resCode: 0, resData: [{productId: 1, productName:"TypeScipt actual ", remark: "remarks "}, {productId: 2, productName:"TypeScipt from start to master "},], message: "success"} render(result)Copy the code
  1. Using type assertions

Use type assertion, tell the compiler exactly what the type is, and the compiler will bypass type checking, right

Render ({resCode: 0, resData: [{productId: 1, productName:"TypeScipt ", remark:""}, {productId: } as ResponseData) render(<ResponseData>{ResponseData: 0, resData: [{productId: 1, productName:"TypeScipt actual ", remark: "remarks "}, {productId: 2, productName:"TypeScipt from start to master "},], message: "success"})Copy the code
  1. Use string index signatures
interface ResultData { productId: number; productName: string; [remark: string]: any; // String index signature}Copy the code

The function interface

  • Function definition:
  1. In TS, the function is defined directly using a variable
let add: (x: number, y: number) => number = (x, y){ return x+y; }; Add (1, 2)Copy the code
  1. Use interfaces to define functions
interface Add { (x: number, y: number): number } let myFunc: Add = function(x, y){ return x+y; }; MyFunc (1, 2);Copy the code
  1. Use type aliases to define functions

Type aliases use the type keyword

type Add = (x: number, y: number) => number
Copy the code

Indexable type of interface

Interface numberIndex {[x: number]: string} let chars: numberIndex = ['A', 'B']Copy the code
Interface stringIndex {[x: string]: string}Copy the code
Interface stringIndex {[x: string]: string [z: number]: number // // Numeric index type 'number' is not assignable to string index type 'string'. } interface stringIndex { [x: string]: any [z: number]: number // Numeric index type 'number' is not assignable to string index type 'string'. }Copy the code

Overhand TypeScipt

For NPM users

npm install -g typescript
Copy the code

Build the first TypeScript file, dada.ts:

function dada(person) {
 return "hello" + person;
}
let user = "jeskson";
document.body.innerHTML = dada(uer);
Copy the code

Compile the code

On the command line, run the TypeScript compiler:

tsc dada.ts
Copy the code

Add type annotation: String

function dada(person: string) {
 return "jeskson"+person;
}
let user = "jeskson";
document.body.innerHTML = dada(user);
Copy the code

Type annotations

Type annotations in TypeScript are a lightweight way to add constraints to functions or variables.

interface

Allows us to implement an interface as long as it contains the required structure of the interface

// implements statement interface Person {firstName: string; lastName: string; } function func(peson: Person) { return person.firstName + person.lastName; } let user = { firstName: "jeskson", lastName: "User" }; document.body.innerHTML = func(user);Copy the code

Class, which supports class-based object-oriented programming

class Student { fullName: string; constructor(public firstName: string, public lastName: string) { this.fullName = firstName + lastName; } } interface Person { firstName: string; lastName: string; } function dada(person: Person) { return person.firstName+person.lastName; } let user = new Student("jeskson"," Jeskson "); document.body.innerHTML = dada(user);Copy the code

Run TypeScript Web applications

Enter the content in index.html:

<! DOCTYPE html> <html> <head><title>TypeScript dada</title></head> <body> <script src="dada.js"></script> </body> </html>Copy the code

object

In JS, object properties can be modified arbitrarily,TS does not allow

Let obj: object = {x: 'a', y: {x: 'a', y: {x: 'a', y: 'b'} obj.x = 3 // Property 'x' does not exist on type 'object'.Copy the code
let obj: {x: string, y: string} = {x: 'a', y: 'b'}
obj.x = 'c'
Copy the code

Symbol

Has a unique value that can be declared explicitly or created directly

let symbol1: Symbol = Symbol() // display declaration let symbol2 = Symbol() // directly create // verify that it is the same object console.log(symbol1 == symbol2) // fasleCopy the code

Undefined and null

// let udf: undefined = undefined let nu: null = null let undf: Undefined = 1 // Type '1' is not assignable to Type 'undefined'. number = undefined // Type 'undefined' is not assignable to type 'number'. let num2: number = null // Type 'null' is not assignable to type 'number'.Copy the code
  • In the TS,Undefined and nullIs a subtype of any type and can therefore be assigned to other types
  • Set to allow assignment to other types

Open tsconfig.js and set strictNullChecks = false(default true)

void,any,never

  • injs,voidThe operator can cause any expression to returnundefined
  • Void 0 // returns undefined
// void
let voidFunc = () => {}
Copy the code
  • any: If no value is specifiedTSThe default isanyType, which can be assigned to any type
  • never: There will never be a type of return value
Never let Error = () => {throw new error ('error')} // Never let Endless = () => { while(true) {} }Copy the code

Deduplicates an object in an array by its value

let listData = [
  { firstName: "dada", lastName: "abc", size: 18 }
}
Copy the code
//js
let obj = {};
listData = listData.reduce((item, next) => {
  if (!obj[next.lastName]) {
    item.push(next);
    obj[next.lastName] = true;
  }
  return item;
}, []);
Copy the code
//ts const obj: {[key: string]: boolean; } = {}; listData = listData.reduce<ListDataItem[]>((item, next) => { if (! obj[next.lastName]) { item.push(next); obj[next.lastName] = true; } return item; } []);Copy the code

It is used in wechat small program developmentTypescript

Module concept

“Internal modules” are now called “command space” and “external modules” are now shortened to “modules”. Module words are executed in their own scope, not in the global scope.

This means that variables, functions, classes, and so on defined in a module are not visible outside the module unless you explicitly export them using one of the export forms.

In contrast, if you want to use variables, functions, classes, interfaces, etc. exported by other modules, you must import them, and use one of the import forms.

Concepts of modules:

We can separate some public functions into a file as a module. The variables, functions and classes in the module are private by default. If we want to access the data in the module externally, we need to expose the data in the module through export. To use the exposed data in the module, import the module with import.

The namespace

Differences between namespaces and modules

  • Namespace: An internal module used to organize code and avoid naming conflicts
  • Module: Short for ts external module
namespace A {
interface Animal {
 name: string;
 eat(): void;
}
class Dog implements Animal {
 name: string;
 constructor(theName: string) {
  this.name = theName;
 }
 eat() {
  console.log('dog');
 }
}
class Cat implements Animal {
 name: string;
 constructor(theName: string) {
  this.name = theName;
 }
 eat() {
  console.log('cat');
 }
}
let dog = new Dog('dogdog');
dog.eat();
}
Copy the code
import {A,B} from './modules/animal';

var dog = new A.Dog('hei');
dog.eat();
Copy the code

A decorator

A decorator is a special type of declaration that can be attached to a class declaration, method, attribute, or parameter to modify the behavior of a class.

In layman’s terms, a decorator is a method that can be injected into classes, methods, and property parameters to extend the functionality of classes, properties, methods, and parameters.

Common decorators are: class decorators, property decorators, method decorators, and parameter decorators

Ornament written:

  • Common decorator (unable to pass parameters)
  • Decorator factory (passable)

Method parameter decorator:

The parameter decorator expression is called as a function at run time. You can use the parameter decorator to add some element data to the class’s prototype, passing in the following three parameters:

  • Constructor of the class for static members and prototype object for instance members
  • Method name
  • The index of a parameter in the function argument list
function logParams(params:any){ return function(target:any,methodName:any,paramsIndex:any){ console.log(params); console.log(target); console.log(methodName); console.log(paramsIndex); } } class HttpClient{ public url:any|undefined; constructor(){} getDate(@logParams('xxx') uuid:any){ console.log(uuid); }}Copy the code

keyof

Key {x: number; y: number; } // type keys = "x" | "y" type keys = keyof Point;Copy the code
Function get(o: object, name: string) {return o[name]} const data = {a: 1, b: 2} function get(o: object, name: string) {return o[name]}Copy the code

Using keyof:

function get<T extends object, K extends keyof T>(o: T, name: K): T[K] {
  return o[name]
}
Copy the code

? : operator

T extends U ? X : Y

type isTrue<T> = T extends true ? true : false
Copy the code

tsconfig.json

The tsconfig.json file specifies the root file and compilation options to compile this project

Tsconfig. json sample file:

//"compilerOptions" can be ignored and the compiler uses the default. // Use the "files" attribute //"files" to specify a list of relative or absolute file paths. { "compilerOptions": { "module": "commonjs", "noImplicitAny": true, "removeComments": true, "preserveConstEnums": true, "sourceMap": true }, "files": [ "core.ts", "sys.ts", "types.ts", "scanner.ts", "parser.ts", "utilities.ts", "binder.ts", "checker.ts", "emitter.ts", "program.ts", "commandLineParser.ts", "tsc.ts", "DiagnosticInformationMap. Generated. Ts"]} / / using "include" and "exclude" attribute / / if "files" and "include" is not specified, // Exclude files specified in "exclude" {"compilerOptions": {"module": "system", "noImplicitAny": true, "removeComments": true, "preserveConstEnums": true, "outFile": ".. /.. /built/local/tsc.js", "sourceMap": true }, "include": [ "src/**/*" ], "exclude": [ "node_modules", "**/*.spec.ts" ] }Copy the code

The view mode: json.schemastore.org/tsconfig.

Go back to my previous articles and you may get more!

  • JS Sunflower treasure Book secret notes, escort for you gold three silver four
  • TypeScript learns early to become competitive in the workplace
  • A qualified junior front-end engineer needs to master module notes
  • More than 234.77 million words in front-end simulation interview
  • Vue.js pen test questions Solve common business problems
  • [Primary] Personally share notes of Vue front-end development tutorial
  • A long summary of JavaScript to consolidate the front end foundation
  • ES6 comprehensive summary
  • Dada front-end personal Web share 92 JavaScript interview questions with additional answers
  • [Illustrated, like collection oh!] Re-study to reinforce your Vuejs knowledge
  • 【 Mind Mapping 】 Front-end development – consolidate your JavaScript knowledge
  • 14 – even liver 7 nights, summed up the computer network knowledge point! (66 items in total)
  • This was my first JavaScript primer
  • LocalStorage and sessionStorage localStorage
  • Drag and drop in HTML5
  • Challenge the front-end HTTP/ECMAScript
  • Must learn must learn – Audio and video
  • 170 Interview questions + answer Learn to organize (conscience making)
  • Front-end HTML5 interviewers and candidates ask and answer questions
  • Ne Zha is sweeping the sea
  • Tencent location service development applications
  • [Advanced] The interviewer asked me how Chrome renders (6000 words)
  • The interviewer started by asking me about Chrome’s underlying principles and HTTP protocol (swastika)
  • Staying up late summed up the “HTML5 Canvas”
  • This /call/apply/bind
  • The HTTP/HTTPS/HTTP2 / DNS/TCP/classic problem
  • Execute context/scope chain/closure/first-class citizen
  • Web page creation basics
  • Learn the summary of HTML5 finger front-end (suggested collection, illustrated)

❤️ follow + like + Favorite + comment + forward ❤️

Likes, favorites and comments

I’m Jeskson, thanks for your talent: likes, favorites and comments, and we’ll see you next time! ☞ Thank you for learning with me.

See you next time!

This article is constantly updated. You can search “Programmer Doraemon” on wechat to read it for the first time, and reply [information] there are materials of first-line big factories prepared by me, which have been included in this article www.1024bibi.com

Star: github.com/webVueBlog/…

  • Hand in your homework technology creators, come here quickly! | creator camp phase ii