当前位置:网站首页>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
边栏推荐
- WIN10环境下配置pytorch
- 爱可可AI前沿推介(6.25)
- Another night when visdom crashed
- C # switch between Chinese and English input methods
- 字符串各操作函数与内存函数详解
- Three lines of code to simply modify the project code of the jar package
- 买基金在哪里开户安全?还请赐教
- 数据在内存中的存储相关内容
- AI assisted paper drawing of PPT drawing
- Fedora 35 deploys DNS master-slave and separation resolution -- the way to build a dream
猜你喜欢

J2EE from entry to earth 01 MySQL installation

KDD 2022 | graphmae: self supervised mask map self encoder

剑指 Offer II 028. 展平多级双向链表

Sword finger offer II 029 Sorted circular linked list

Detailed explanation of string operation functions and memory functions

[pit avoidance refers to "difficult"] antd cascader implements new customized functions

AGCO AI frontier promotion (6.25)

初始c语言的知识2.0

几分钟上线一个网站 真是神器

515. Find Largest Value in Each Tree Row
随机推荐
Koa 框架
nacos无法修改配置文件Mysql8.0的解决方法
Heavyweight live | bizdevops: the way to break the technology situation under the tide of digital transformation
Solve the problem that yarn cannot load files in vs Code
[pit avoidance refers to "difficult"] halfcheckedkeys rendering problem in semi selected status of antd tree
量化交易之回测篇 - 期货CTA策略实例(TQZFutureRenkoScalpingStrategy)
解析数仓lazyagg查询重写优化
Summer Ending
学习编程的起点。
Sword finger offer 04 Find in 2D array
Sword finger offer II 029 Sorted circular linked list
Uncover gaussdb (for redis): comprehensive comparison of CODIS
數據在內存中的存儲相關內容
Pointer, it has to say that the subject
[flask tutorial] flask overview
[machine learning] what is machine learning?
Sword finger offer day 1 stack and queue (simple)
Fedora 35 deploys DNS master-slave and separation resolution -- the way to build a dream
Oral English - continuous reading
J2EE从入门到入土01.MySQL安装