当前位置:网站首页>Drago Education - typescript learning
Drago Education - typescript learning
2022-06-25 13:17:00 【liminla!】
TypeScript
1、 Strong type and weak type ( Type safety )
Strong type :
At the language level, the actual parameter type of the function must be the same as the formal parameter type: Strong typing does not allow any form of implicit conversion
Strong type advantage
- Mistakes are exposed earlier
- Code is smarter , More accurate coding
- Refactoring is more robust
- Reduce unnecessary type judgments
Weak type :
The language level does not restrict argument types: Weak types allow implicit conversions
Weak type problems
- Some types of problems in the program need to wait until run time to find
- Ambiguous types may cause function functions to change
2、 Static and dynamic types ( Type checking )
Static type :
The type of a variable is determined when it is declared , And the type cannot be changed after declaration
Dynamic type :
The type can only be defined during the operation stage , And the variable type can change at any time: Variables have no type , The values stored in variables are typed
Different language types

3、JavaScript Own type system problems
Weakly typed and dynamically typed , Missing the reliability of the type system
4、Flow Static type checking scheme
javascript Type checker for
5、TypeScript Language specification and basic application
TypeScript yes JavaScript Superset ( Extension set ), The second language in the front-end field 、 Progressive language
advantage
- Any one JavaScript The running environment supports
- More powerful , More sound and perfect ecology
shortcoming
- Language itself has many concepts
- At the beginning of the project , It will increase some costs

Use
Installation and startup
yarn init --yes
yarn add typescript --dev
//a.ts
const hello=(name:string)=>{
console.log(`hello,${
name}`);
}
hello('TypeScript')
// Console input yarn tsc a.ts// The root directory , And the directory does not contain Chinese . Generate
//a.js
var hello = function (name) {
console.log("hello,".concat(name));
};
hello('TypeScript');
The configuration file
yarn tsc --init
Generate tsconfig.json file
"target": "es2016", // Translate all new features into es6 Standard code
"module": "commonjs", // How the output code is modularized
"rootDir": "src", // Configure the source code folder
"outDir": "dist", // The folder to which the compilation results are output
"sourceMap": true, // Open source mapping
"strict": true, // Strict mode
Raw data type
const a:string='foo'
const b:number=10
const c:boolean=true
// const d:boolean=null // Not in strict mode
const e:void=undefined
const f:null=null
const g:undefined=undefined
const h:symbol=Symbol()//es2016 newly added
const i:bigint=123n //es2020 newly added
typeScript Display Chinese error message
yarn tsc --locale zh-CN
perhaps VS code Set search typescript locale Unified change to zh-CN // Generally not recommended
TypeScript object type
Other types besides the original type
Use object literal or interface to define
const obj:object=function(){}//[] //{}
const obj:{foo:number,bar:string}={foo:123,bar:'string'}
TypeScript An array type
const arr1:Array<number>=[1,2,3]
const arr2:number[]=[1,2,3]
function sum(...args:number[]){
console.log(111);
return args.reduce((prev,current)=>prev+current,0)
}
TypeScript A tuple type
const tuple:[number,string]=[18,'str']
TypeScript Enumeration type
Generally, objects are used to simulate enumerations
// Define a numeric enumeration
enum enumConst{
up = 1,
down,
left = 10,
right
};
console.log(enumConst[1]);
console.log(enumConst[2]);
console.log(enumConst[3]);
console.log(enumConst[4]);
console.log(enumConst[44]);
// Output :
// up
// down
// left
// right
// undefined
console.log(enumConst.up);
console.log(enumConst.down);
console.log(enumConst.left);
console.log(enumConst.right);
// Output :
// 1
// 2
// 10
// 11
TypeScript Function type
function func1(a:number,b:number):string{
return 'func1'
}
function func2(a:number,b:number=10):string{// Default ( It has to be at the end )
return 'func3'
}
function func3(a:number,b?:number):string{// Optional ( It has to be at the end )
return 'func3'
}
function func4(a:number,b?:number,...rest:number[]):string{// Optional ( It has to be at the end )
return 'func4'
}
const func5:(a:number,b:number)=>string=function(a:number,b:number):string{
return 'func5'
}
TypeScript Any type
function any1(value:any){// Easy not to use
return value
}
TypeScript Types of assertions
Type assertion is not a type conversion , After compilation, it does not exist
const nums=[100,200]
const res=nums.find(i=>i>1)
const num1=res as number
const num2=<number>res //jsx Out of commission
TypeScript Interface interface
Contract object members and member types: Used to make type constraints for structured data
interface Post {
title: string// It can be for ; , You can also do without symbols
name: string
age: number
sex?:number// Optional members
readonly id:string//readonly Read only members , It cannot be modified later
[key:string]:string// Dynamic members , In the example, it means string Key and value of type
}
function printPost(post: Post) {
console.log(post.title);
console.log(post.name);
console.log(post.age);
}
printPost({
title: 'happy study day',
name: 'zangsan',
age: 18
})
TypeScript class Basic use of
class Person{
// Class attributes must have an initial value
public name:string//name:string='init name'
protected age:number // Protection properties , Can be accessed by subclass
private id:string // Private property , Only internal access
constructor(name:string,id:string){// Assign values through constructors
this.name=name
this.age=18
this.id=id
}
sayHi(msg:string):void{
console.log(` I am ${this.name},age ${this.age}`);
console.log(this.id);
}
}
class Son extends Person{
constructor(name:string,id:string){
super(name,id)
console.log(this.age);
}
}
let tom=new Person('tom','abc111')
console.log(tom.name);
console.log(tom.age);// attribute “age” The protected , Only in class “Person” And its subclasses .
console.log(tom.id);// attribute “id” For private property , Only in class “Person” Medium visit .
TypeScript Classes and interfaces
interface EatAndRun{
eat(food:string):void
run(distance:number):void
}
interface See{
see(color:string):void
}
class Person implements EatAndRun,See{
eat(food:string):void{
console.log(` Eat watermelon :${food}`);
}
run(distance:number):void{
console.log(` Jump rope :${distance}`);
}
see(color:string):void{
console.log(` Jump rope :${color}`);
}
}
class Animal implements EatAndRun{
eat(food:string):void{
console.log(` eat :${food}`);
}
run(distance:number):void{
console.log(` jump :${distance}`);
}
}
TypeScript abstract class
// The parent class has abstract methods, and the child class must implement
abstract class Animal1{
eat(food:string):void{
console.log(` eat :${food}`);
}
abstract run(distance:number):void
}
class Dog extends Animal{
run(distance:number):void{
console.log(' crawl ',distance);
}
}
const dog=new Dog
dog.eat(' The bone ')
dog.run(100)
TypeScript Generic
No type was specified when defining the function interface class , Define when using
function ab(length:number,value:number):number[]{
const arr=Array<number>(length).fill(value)
return arr
}
function abc(length:number,value:string):string[]{
const arr=Array<string>(length).fill(value)
return arr
}
function abcd<T>(length:number,value:T):T[]{
const arr=Array<T>(length).fill(value)
return arr
}
// const res=ab(3,10)
const res=abc(3,'str')
// const res=abcd<string>(3,'aaa')
TypeScript Type declaration
Member definition does not declare an explicit type , Declare when using
import {
camelCase} from 'lodash'
declare function camelCase(input:string):string
边栏推荐
- Native JS --- infinite scrolling
- Of binary tree_ Huffman tree_ Huffman encoding
- Update PIP & Download jupyter Lab
- JVM parameter interpretation
- CUDA error: unspecified launch failure
- 揭秘GaussDB(for Redis):全面对比Codis
- Koa 框架
- QT display ffmpeg decoded pictures
- [pit avoidance means "difficult"] to realize editable drag and drop sorting of protable
- leetcode:456. 132 模式【单调栈】
猜你喜欢

Using CMD (command prompt) to install MySQL & configure the environment

About data storage in memory

剑指Offer 第 2 天链表(简单)

Resolution of PPT paper drawing

. NET in China - What's New in . NET

J2EE from entry to earth 01 MySQL installation

golang键盘输入语句scanln scanf代码示例

Sword finger offer day 3 string (simple)

解析数仓lazyagg查询重写优化

Maui's learning path (II) -- setting
随机推荐
Of binary tree_ Huffman tree_ Huffman encoding
KVM 脚本管理 —— 筑梦之路
剑指Offer 第 2 天链表(简单)
[pit avoidance means "difficult"] to realize editable drag and drop sorting of protable
Serenvlt first met
Confusion caused by the ramp
Online service emergency research methodology
Capabilities required by architects
字符串各操作函数与内存函数详解
QT mouse tracking
20220620 interview reply
关于数据在内存中存储的相关例题
KVM script management - the road to dream
leetcode - 384. 打乱数组
Which Chinese virtual human is better? Sullivan, IDC: Xiaobing Baidu Shangtang ranks in the first echelon
Django框架——缓存、信号、跨站请求伪造、 跨域问题、cookie-session-token
Custom vertical table
數據在內存中的存儲相關內容
MySQL learning notes
Common colors for drawing