当前位置:网站首页>Introduction to typescript and basic types of variable definitions

Introduction to typescript and basic types of variable definitions

2022-06-23 08:17:00 wendyTan10

( One )TypeScript An introduction to the

know typeScript

TypeScript Official website :TypeScript is a typed superset of JavaScript that compiles to plain JavaScript.
GitHub Statement :TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
Translate TypeScript It's a type of JavaScript Superset , It can be compiled into ordinary 、 clean 、 complete JavaScript Code
Understand this sentence on the official website :

  • As opposed to TypeScript( abbreviation ts) yes JavaScript( abbreviation js) The enhanced ;
  • js All the features you have ,ts All for ; It follows ECMAScript Standards for , therefore ES6、ES7、ES8 Wait for the new grammar standard , It's all for ;
  • And on the linguistic level , It's not just about adding type constraints , And it includes some grammatical extensions , For example, enumeration type (Enum)、 A tuple type (Tuple) etc. ;
  • TypeScript While implementing new features , Always keep and ES Standard synchronization is even leading ;
  • also TypeScript It will eventually be compiled as JavaScript Code , So you don't have to worry about its compatibility , You don't need to build with Babel Such a tool ;
  • therefore , We can TypeScript Understood as more powerful JavaScript, Not only JavaScript More secure , And it has brought many easy-to-use features ;

TypeScript Compiler environment for

TypeScript It will eventually be compiled as JavaScript To run the , So we need to build the corresponding environment ;
We need to install... On the computer TypeScript, So you can get through TypeScript Of Compiler Compile it into JavaScript;

#  Installation command  npm install typescript -g
#  View version  tsc --version

TypeScript Operating environment

Two solutions to configure the view run :

  • Mode one :webpack Configuration of : Click to browse coderwhy The article written by the author
  • Mode two : Use ts-node, Direct operation ;
    install ts-node:npm install ts-node -g
    in addition ts-node Need to rely on tslib and @types/node Two bags :npm install tslib @types/node -g
    Now? , We can go straight through ts-node To run the TypeScript Code for :ts-node math.ts

( Two ) Declaration of variables

stay TypeScript Variables defined in need to be specified identifier The type of . So the complete declaration format is as follows :

//  Assign values according to the defined data types 
var/let/const  identifier :  data type  =  assignment ;
const name:string = 'wendy';

The above is support JavaScript The schema definition of , You may not add data types , but typescript Its own characteristics help us infer the corresponding variable types ;
Like the one below name Initial assignment string After the type , Cannot be changed to non string type
 Insert picture description here

( Two )JavaScript and TypeScript Data type of

JavaScript and TypeScript Inclusion relationship between data types of :
 Insert picture description here

(1) Basic data types and definitions :

  • number type ;
  • boolean type ;
  • string type ;
  • Array type ;
    const list1:string[] = ['1', '22']; //  Recommended 
    const list2:Array<string> = ['1', '22']; //  stay react There are often <div></div> Writing , To avoid conflict 
    
  • Object type ;
  • Symbol type ;
  • null and undefined type ;
  • any type ;
    // any Type is a bit like a flattering TypeScript methods , Just don't define the type , Any type can be implemented 
    let name:any = 'wendy';
    	name = 'Bond';
    	name = 14555;
    	name = true;
    
  • unknown type
     // unknown yes TypeScript A special type in , It is used to describe variables of uncertain type ;
     //  be relative to any , Only for unknown After type safety testing , To allow specific operations to be performed .
     let score: unknown = 98;
     let num = Math.round(score); //error
    
    Before you type check it ,ubnknow A variable of type cannot perform any operation .
     Insert picture description here
    Only for unknown After type safety testing , To allow specific operations to be performed ;
    let score: unknown = 98;
    if(typeof score === "number") {
          
    	let num = Math.round(score); // ok
    }
    
  • void type
    //  Function has no return value type ;
    function sum(num1: number, num2: number): void {
          
    	console.log(num1 + num2);
    }
    
  • never type
    never A type that represents a value that will never happen , For example, an infinite loop or a function that throws an error :
    //  advance 
    //  Encapsulate a core function 
    function handleMessage(message: string | number | boolean) {
          
    	switch (typeof message) {
          
    		case 'string':
    			console.log("string How to handle message")
    			break;
    		case 'number':
    	      console.log("number How to handle message")
    	      break
    	    case 'boolean':
    	      console.log("boolean How to handle message")
    	      break
    	    default:
    	      const check: never = message
    	  }
    }
    //  Functions that throw errors 
    function loopErr(): never {
          
    	throw new Error();
    }
    
  • tuple type - A tuple type
    const tInfo: [string, number, number] = ["why", 18, 18];
    const item1 = tInfo[0]; // why, And the type is string type 
    const item2 = tInfo[1]; // 18, And the type is number
    
    tuple and Array The difference between arrays :
    const info:(string|number)[] = ["why", 18, 18];
    const item1 = info[0]; //  The type cannot be determined 
    
    const tInfo: [string, number, number] = ["why", 18, 18];
    const item2 = tInfo[0]; //  Fixed time string type 
    

(2) Supplement to type definition

Automatic derivation type :

//  Add type annotation to the parameter : num1: number, num2: number
//  Add type comments to the return value : (): number
//  In development , In general, you can not write the type of return value ( Automatic derivation )
function sum(num1: number, num2: number) {
    
  return num1 + num2
}
sum(123, 321); //  The derived type is number

const names = ["abc", "cba", "nba"]
// item Derived from the context of ,  At this time, you can not add type annotations 
//  Functions in context :  You can not add type annotation 
names.forEach(function(item) {
    
  console.log(item.split(""))
})

Type derivation item yes string type :
 Insert picture description here
Definition of object type :

// Point: x/y ->  object type 
// {x: number, y: number}
function printPoint(point: {
    x: number, y: number}) {
    
  console.log(point.x);
  console.log(point.y)
}
printPoint({
    x: 123, y: 321})

Use of optional types :

// Point: x/y/z ->  object type 
// {x: number, y: number, z?: number}
function printPoint(point: {
    x: number, y: number, z?: number}) {
    
  console.log(point.x)
  console.log(point.y)
  console.log(point.z)
}

printPoint({
    x: 123, y: 321})
printPoint({
    x: 123, y: 321, z: 111})

Use of union types : |

// number|string  Joint type 
function printID(id: number|string|boolean) {
    
  //  When using values of union type ,  Special care is needed 
  // narrow:  narrow 
  if (typeof id === 'string') {
    
    // TypeScript Help determine id It must be string type 
    console.log(id.toUpperCase())
  } else {
    
    console.log(id)
  }
}

printID(123)
printID("abc")
printID(true)

Relationship between optional types and object types :

//  When a parameter is an optional type ,  This parameter is equivalent to : type |undefined  The type of Union 
// message?: string  Equate to  message: string | undefined
function foo(message?: string) {
    
  console.log(message)
}

The use of type aliases , Use type Keywords to define :

// type Used to define type aliases (type alias)
type IDType = string | number | boolean
type PointType = {
    
  x: number
  y: number
  z?: number
}
function printId(id: IDType) {
    
}
function printPoint(point: PointType) {
    
}

(3) Type assertions use :

  • Types of assertions as();
    Type assertions are used to force a variable to change its type at compile time , Usually used for Joint type ,any, And parent-child classes Assertions between , Usually this happens when you know clearly that an entity has a more exact type than its existing type ; There are two forms of writing :
    1. value as type
    2. <type>value
let data : any = "Hello";
let len : number = (<string>data).length;
console.log(len);// Output 5
len = (data as string).length;
console.log(len);// Output 5

Examples of use :

// 1. Types of assertions  as
const el = document.getElementById("why") as HTMLImageElement
el.src = "url Address "
// 2. Other cases : Person yes Student Parent class of 
class Person {
    
}
class Student extends Person {
    
  studying() {
    
  }
}
function sayHello(p: Person) {
    
  (p as Student).studying()
}
const stu = new Student()
sayHello(stu)

// 3. understand : as any/unknown
const message = "Hello World"
const num: number = (message as unknown) as number
  • Use of non empty type assertions : !
// message? -> undefined | string
function printMessageLength(message?: string) {
    
  // if (message) {
    
  // console.log(message.length)
  // }
  // vue3 Source code 
  console.log(message!.length)
}

printMessageLength("aaaa")
printMessageLength("hello world")
  • Use of optional chains : ?
// ?  Code is not required 
type Person = {
    
  name: string
  friend?: {
    
    name: string
    age?: number,
    girlFriend?: {
    
      name: string
    }
  }
}
const info: Person = {
    
  name: "why",
  friend: {
    
    name: "kobe",
    girlFriend: {
    
      name: "lily"
    }
  }
}
console.log(info.name)
// console.log(info.friend!.name)
console.log(info.friend?.name)
console.log(info.friend?.girlFriend?.name)

原网站

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