当前位置:网站首页>Typescript Basics

Typescript Basics

2022-07-23 20:59:00 Aboci Bang

TS stay js Many are added on the basis of java The characteristics of language
Global installation :
typescript: npm install -g typescript
perform ts file : npm i -g ts-node
Generate tsconfig.json The configuration file :tsc -init

1. use VSCode Create a .ts file
 Insert picture description here
2. Strong type – Specify the variable type for the variable

var uname:string
uname = "1"
uname = null  //no
uname = undefined  //no
uname = 1  //no
uname = {
    }  //no
uname = []  //no
uname = function(){
    }  //no
var uname:string
uname = "1"
function a(uname:string){
     // Specify the type for parameter display 
  return uname.split("");
}
a('qwe')// Automatically monitor whether the parameter types match 

 Insert picture description here

3. ts The file cannot run on the browser , You need to perform ts command :tsc 01.ts
ts Will detect 【 At the same time 】 In file Whether there is a naming conflict
 Insert picture description here
4. Basic data type

var a:null
a = null

var b:undefined
b = void 0

var c:string
c = 1+""

var d:number
d = Math.PI
d = Number.MAX_SAFE_INTEGER
d = 2 ** 24
var e:any // Any type 
e = {
    }
e = []

var f: string | boolean // Mixed type 
f = `${
      a}`
f = true

5. An array type

// Specify the array element type   by  number
// Basic writing -01
var TS_arr:Array<number> = [1,2,3,4,null,undefined]
// Basic writing -02
var TS_arr:number[] = [1,2,3,4]
// Multiple types 
var TS_arr:(number | string |null | undefined)[] = [1,2,3,4,null,undefined]

// Array object writing  -01
var cc:{
    a:number,b:string}[] = [
  {
    a:1,b:"aaac"},
  {
    a:3,b:"cccc"}
]
// Array object writing  -02
type t = {
    a:number,b:string}
var cc:t[] = [
  {
    a:1,b:"aaac"},
  {
    a:3,b:"cccc"}
]
// Array object writing  -03
class t{
    
  a:number
  b:string
}
var cc:t[] = [
  {
    a:1,b:"aaac"},
  {
    a:3,b:"cccc"}
]

6. Interface

interface ts_json {
    
  a:boolean,
  b:string,
  c?:number, //  Added a question mark to represent  c Attributes can be left blank 
  [propname:string]:any, // Write any attribute   Not constrained  ( The attribute name is string type   Attribute values are of any type ) 
  say():string, //  There has to be say Method   And the return value is string type 
}

// Constrain the object literal 
var ts_json_01:ts_json = {
    
  a:true,
  b:"",
  c:1,
  d:true,
  e:undefined,
  say() {
    
      return " The return value is defined in the interface string type "
  },
}

// Yes   Class 
class A implements ts_json{
    
  a = true
  b = ""
  c = 1
  say(){
    
    return " The return value is defined in the interface string type "
  }
}

// Interface inheritance 
interface ts_son extends ts_json{
    
  www() : string
}

class B implements ts_son{
    
  a = true
  b = ""
  c = 1
  say(){
    
    return " The return value is defined in the interface string type "
  }
  www(){
    
    return "ts_son Inherited  ts_json  So this class not only has to accept  ts_json Interface constraints   You have to add one  ts_son Bound by  www Method "
  }
}

console.log(ts_json_01);

7. object type

// Interface constraint object 
interface ts_json {
    
  a:boolean,
  b:string,
  c?:number, //  Added a question mark to represent  c Attributes can be left blank 
}
var ts_json_01:ts_json = {
    
  a:true,
  b:"",
}
console.log(ts_json_01);

// Another way of writing 
const aa: {
    
  a:boolean,
  b:string,
  c:number,
} = {
    
  a:true,
  b:"",
  c:123,
}
console.log(aa);

8. Class modifier publicprotectedprivate

class Limit{
    
  public a=1 // Instantiated objects are available  
  protected b=2 //  Classes and subclasses are available internally  
  private c=3 //  Available within the current class  
}
//ts Define a class 
const a :Limit = new Limit();
console.log(a.a)

9. Type notes Type inference

// Type notes : Manually add the type of variable 
// Type inference : The program can infer the types of some variables   So there is no need to add 
let a = 1;
a = "" // Report errors 

10. Function parameter type and return type detection

// There is a return value writing 
let a = 1;
function aa(b:number):number{
    // Prevent unexpected type changes 
  return b
}
aa(a)
// No return value 
function aa(b:number):void{
    // Prevent the occurrence of return sentence   Just write one  return  No mistakes 
  console.log(b+"")
  return "";// Report errors 
}
aa(a)
// Carry out a dead cycle 
let a = 1;
function aa(b:number):never{
    // Keep the function executing 
  throw new Error()
}
function bb(b:number):never{
    // Keep the function executing 
  while(true){
    }
}

// Parameters are objects 
function a({
     aa}:{
     aa:number}){
    
  return aa
}
a({
    aa:1})

11. Tuples Solve the different order of array types and elements

// One dimensional array 
const arr :[string,number] = ["",1]
// Two dimensional array 
const arr :[string,number][] = [
  ["",1],
  ["",1]
]

12. ts Class static getter setter

class A {
    
  readonly b :string = "readonly keyword   Set property read only "
  constructor(private _a:string){
    } // In the constructor   Define a  _a  attribute   Simplify the writing of defining attributes 
  get a(){
     // getter
    return this._a + "_get"
  }
  set a(val){
     // setter
    this._a = val + "_set"
  }
  static saw(){
      // Define static methods   Directly by class name  .  Method name call   No more instantiation of objects 
    console.log("saw Method ")
  }
}
let aa = new A("sss")
aa.a = " modify a__"
//aa.b = " modify b attribute " // Report errors 
console.log(aa.a)
// Call static methods 
A.saw()

13. ts abstract class

//abstract  Keywords define abstract classes   and   Abstract method 
abstract class A{
    
  abstract sss():any
}
class B extends A{
    
  sss() {
    
      console.log("B Class needs to be defined  sss Method body of ");
  }
}

14. tsconfig.json Files are often used To configure Just untie the notes

{
    
  "include": ["01.ts"], // Compile only  01.ts
  "exclude": ["02.ts"], // Compile except  02.ts file 
  "files": ["*.ts"],// compile   All the files 
  "compilerOptions": {
    
	"removeComments": true,  // Remove annotations   At the time of execution   Direct terminal input  tsc that will do 
	"strict": true,   // Turn on strict mode 
	"noImplicitAny": true,// Note types are allowed   by any  Of   There is no need to make a special statement  any
	"rootDir": "./src",  // Entry file path 
    "outDir": "./build", // Export file path 
    "sourceMap": true, // After compiling   file   Mapping with source files   Convenient for troubleshooting 
    "noUnusedLocals": true,  //  Unused variables   No more packaging 
  }
}

15. Joint type and Type guard

interface AI {
    
  a:string,
  ai():any
}
interface BI {
    
  b:string,
  bi():any
}
// Joint type 
interface AI {
    
  a:string,
  ai():string
}
interface BI {
    
  b:string,
  bi():string
}

function jw(j:AI | BI){
    // Joint type 
  // Type guard   Judge   Which interface does it belong to 
  let a = (j as AI).a;
  console.log("a=>",a);
  if(a){
     
    let ai = (j as AI).ai;
    console.log(ai());
  }
  let b = (j as BI).b;
  console.log("b=>",b);
  if(b){
    
    let bi = (j as BI).bi;
    console.log(bi());
  }
}
jw({
    a:"aaa",ai(){
    return " Called ai Method "}})
jw({
    b:"bbb",bi(){
    return " Called bi Method "}})

16. Enumeration type

enum TYPE {
     // Define enumeration types   The default from the 0 Start   It can also be set manually like this 
  A = 1,
  B = 2,
  C = 3,
}
// Reverse query enumeration properties 
console.log(" The check A=>", TYPE[1]);
function F(type: any) {
    
  switch (type) {
    
    case TYPE.A:
      console.log("case_a");
      break;
    case TYPE.B:
      console.log("case_b");
      break;
    case TYPE.C:
      console.log("case_c");
      break;
  }
}
F(TYPE.B);

17. Generic It's like a parameter Pass a type as a parameter

// Pass the type as a parameter 
// Basic generics  T For generics 
function A<T>(a: T, b: T) {
    
  console.log(a, b);
}
A<string>("1", "2");
A<number>(1, 2);
// Define multiple generics 
function D<T, P>(a: T, b: P) {
    
  console.log(a, b);
}
D<string, number>("1", 1);
// Array generics  T For generics 
function B<T>(a: Array<T>) {
    
  console.log(a);
}
B<number>([1, 2]);
// Kind of generic 
class AA<T> {
    
  constructor(private a: T) {
    }
  say_a(): T {
    
    return this.a;
  }
}
let a = new AA<string>("AA Incoming parameter ");
console.log(a.say_a());
// Generic inheritance   There must be something in the agreement 
interface J {
    
  name: string;
}
function JC<T extends J>(jc: T) {
    
  console.log(jc);
}
JC({
     name: "1" }); // J  in   One is required  name attribute 
// Generic constraint 
function YS<T extends string | number>(jc: T) {
     // Generics can only   From the type  string  and  number in   choice 
  console.log(jc);
}
YS("ys Parameters ");

18. Namespace Wrap code in namespaces Prevent global code pollution Achieve modularity Namespaces can be nested

// Define the namespace  
namespace N {
    
  class A {
    
    constructor(public a: string) {
    
      console.log(a);
    }
  }
  class B {
    
    constructor(public b: string) {
    
      console.log(b);
    }
  }
  class C {
    
    constructor(public c: string) {
    
      console.log(c);
    }
  }
  // If you want to use it outside   need  export  Expose 
  export class Main {
    
    constructor() {
    
      new A("aaaa");
      new B("bbbb");
      new C("cccc");
    }
  }
}
let m = new N.Main();

Technical references b standing :【 Technology is fat 】TypeScript From getting started to mastering video tutorials -2020 New edition

TS Official website :https://www.tslang.cn

Blog for so long I found that blogs can be sorted out We don't often use but important knowledge points that are easy to forget , More importantly, learning ability has been greatly improved , For so long I still feel that blogging is never just about doing oneortwo things , Instead, your comprehensive ability has been raised to a certain height , Personally, I think this is the best way to learn .

原网站

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