TypeScript prelude

Article description: This article is the notes and experience of the front-end training camp of Regao. If there is something wrong, I hope you can point out and teach, thank you!

TypeScript can greatly improve the reliability of the code. This series of articles mainly introduces:

  • Strong type and weak type
  • Static type and dynamic type
  • JavaScript's own type system problem
  • Flow static type checking scheme
  • TypeScript language specification and basic application

1. Type system: strong type and weak type

  • Strong type and weak type (from the perspective of type safety): The type of the actual parameter of the restricted function at the language level must be the same as the type of the formal parameter

class Main{
    static void foo(int num){// 强类型,接收一个整型的参数,调用时就不允许传入其它类型的值
        System.out.println(num);
    }

    public static void main(String[] args){
        Main.foo(100);// ok
        Main.foo('100');// error "100" is a string
        Main.foo(Integer.parseInt("100"))//ok  传入前转化成整型的数字
    }
}
//弱类型,弱类型语言层面不会限制实参的类型
function foo(num){// 调用时任然可以传入任意类型数据,语法上是不会报错的,运行上可能出问题
    console.log(num)
}

foo(100) //ok
foo('100')//ok
foo(parseInt('100'))//ok

Since this distinction between strong and weak types is not defined by an authority at all, strong types have stronger type constraints, while weak types have almost no constraints. Strongly typed languages ​​do not allow arbitrary implicit type conversions, and if Type language allows arbitrary data implicit type conversion, for example, what we need is a number, and you can put a string. The characteristics of variable types that are allowed to change at any time are not the difference between strong and weak types. Python is a strongly typed language, but variables can still be typed at any time

Two, static type and dynamic type

  • Static type: the type of a variable is clear when it is declared, and after the declaration, its type is not allowed to be modified

  • Dynamic type: The variable type can be clarified at the runtime, and the variable type can be changed at any time

  • It is also allowed to be assigned a string during operation. Variables in a dynamically typed language have no type, and the value stored in the variable is of the roommate type. JavaScript is a standard dynamically typed language

var foo = 100

foo = 'bar' //ok 运行过程中被赋予字符串,也是允许的,动态类型语言中的变量没有类型,
//变量中存放的值室友类型的,JavaScript就是一门标准的动态类型语言

console.log(foo)
  • Weak type is dynamic type, and strong type is static type. This statement is incorrect

 JavaScript type system characteristics: weak type and dynamic type (type) lack the reliability of the type system (unreliable), the earlier javascript application is simple, the type restriction will be more troublesome, JavaScript does not have a compilation link, it is set as a static language Doesn't make sense (static language needs to be checked at compile time)

Third, the weak type problem

Problems caused by weak JavaScript typing

  • Because of the weak type relationship, type exceptions in the program need to be discovered at runtime

const obj ={}

obj.foo()//obj.foo is not a function  运行时才报错

setTimeout(() =>{
    obj.foo()//在刚刚启动运行时还没发现异常,等到这行代码执行了才抛出这个异常,如果测试过程中没测到,这个就是个隐患,若是强类型,则直接报错。
},1000000)
  • Because of the weak type relationship, the function of the function may change due to the unclear type

function sum(a,b){
    return a+b
}

console.log(sum(100,100)) //200
console.log(sum(100,'100'))//100100 直接拼接了,若是强类型,语法上行不通
  • Because of the weak type relationship, we cause the wrong usage of the object indexer

const obj = {}

obj[true] = 100

console.log(obj['true']) // 100 如果说我们不知道对象属性名会自动转换成字符串的特点,那这里可能就会感觉很奇怪,这种奇怪的根源就是我们用的是比较随意的弱类型语言,强类型则直接报错

Gentlemen agree that there are hidden dangers, and mandatory requirements are guaranteed

Fourth, the advantages of strong types

  • Errors are exposed earlier and can be exposed in the coding stage

  • Code is smarter, coding is more accurate

  • Refactoring is more reliable

  • Reduce unnecessary type judgment

Five, FLOW quick start 

Flow: javaScript type checker, compared to TypeScript is just a small tool, Flow is a module of npm to work. Flow is a static type checking tool for JavaScript code produced by Facebook. Used to find type errors in JavaScript code.

function sum(a:number,b:number){//x,y的类型时number,返回的值的类型时number
    return a+ b
}

sum(100,100)

sum('100','100')

The installation process can use yarn and npm to install, it is recommended to use yarn, because the installation will be faster.

  • Initialize the module

yarn init -yes

  • Install flow
  • yarn add flow-bin -dev
  • Use flow class annotations

1. Must be marked at the beginning of the file: @flow

2. Turn off vscode syntax verification: search for JavaScript validate, find enable, uncheck

// @flow

function sum(a:number, b:number) {
	return a + b;
}

sum(100, 100)
sum('100', '100')

let num:number = 100
num = '100'

 

start using:

yarn flow init
yarn flow  # 第一次会很慢,后续会很快
# yarn flow stop # 结束flow

#Error ---------------------------------------------------------------------------------------------------- 01/01.js:8:12

#Cannot call `sum` with `'100'` bound to `b` because string [1] is incompatible with number [2]. [incompatible-call]

#   01/01.js:8:12
#   8| sum('100', '100')
#                 ^^^^^ [1]

#References:
#   01/01.js:3:26
#   3| function sum(a:number, b:number) {
#                               ^^^^^^ [2]

Six, Flow compile and remove annotations

  • Solution 1: Automatically remove type annotations, officially provided modules:
yarn add flow-remove-types --dev
yarn flow-remove-types . -d dist //第一个命令:.  为文件所在位置(当前目录)  -d 指定转换后的输出目录,我们放在dist文件下
  • Option 2: babel
yarn add @babel/core @babel/cli @babel/preset-flow --dev

Then add the project file .babelrc to the project, and then enter in the file:

{
    "presets":["@babel/preset-flow"]
}

Then use the command line

yarn babel src -d dist

Seven, Flow development tool components

More intuitively reflect the problems in the current code. VS Code search plug-in flow language support, the official plug-in provided by flow, can display type abnormalities in real time. By default, after modifying the code, you need to re-save it before detecting type anomalies.

Flow official website: https://flow.org/en/docs/editors

Eight, type inference

Flow supports type inference during the code writing process. For example, in the following code, you need to calculate the square of a number. When a non-numeric type is passed in, flow will prompt the code and throw a type error.

// @flow

function square(n: number) {
	return n * n;
}

square('100')

Nine, type annotations

In most cases, flow can help us infer the specific types of variables or parameters, so from this perspective, there is no need to add type annotations to all members, but adding type annotations can more clearly limit the type and It is also more helpful to understand the code here later, so we still use type annotations as much as possible. Type annotations can also be used to mark the type of variables and the type of function return values.

let num:number = 100;
// num = 'string',此时只能赋值数字类型

function foo():number {
    return 100
}
// 此时函数只能返回数字类型,如果函数没有返回值,默认返回undefined,那么也会提醒报错。没有返回值的函数,我们需要将函数返回值类型标注为void
function foo():void {
}

Ten, primitive types

There are many types used in flow. The simplest is the primitive data types in JavaScript. There are currently 6 primitive types, number, boolean, string, null, undefined, and symbol.

/**
 * 原始类型
 *
 * @flow
 */

const a: string = 'foobar'

const b: number = Infinity // NaN // 100

const c: boolean = false // true

const d: null = null

const e: void = undefined

const f: symbol = Symbol()

Eleven, array type

/*
数组类型
@flow

*/

const arr1:Array<number> = [1,2,3] // 表示全部由数字组成的数组
const arr2:number[] = //同样可以表示全部由数字组成的数组
//元组
const foo:[string,number] = ['foo':100]//只能够存放包含两位元素的数组,第一位是字符串,第二位是数字,对于这种固定长度的数组称为元组,一般这种元祖我们在一个函数当中同时要去返回多个返回值的时候,我们就可以使用这种元组的数据类型

12. Object type

/*
    对象类型
    @flow
*/

const obj1:{foo:String,bar:number} ={foo:'string',bar:100}

const obj1:{foo?:String,bar:number} ={bar:100}// 属性后面添加问号表示可有可无的了

const obj3:{[string]:string} = {}//键和值都设为string类型,这种类型限制的意思是表示当前对象允许添加任意类型的键,不过键和值的类型都必须是字符串

obj3.key1 = 'vlaue1'
obj3.key2 = 'value2'

Thirteen, function type

/*
    函数类型

    @flow

*/

function foo(callback:(string,number) => void){ // 接收参数类型分别为字符串和数字,该函数的返回值为没有(void)
    callback('string',100)
}

foo(function (str,n){
    // str => string
    // n => number
})

14. Special types

/*
    特殊类型

    @flow

*/

cosnt a:'foo' = 'foo'//字面量类型:用来限制我们的变量必须是某一个值,a变量当中只能够存放这个值'foo'

const type:'success' |'warning'|'danger'='success' //只能存放这三种值之一

//使用type关键词去单独的声明一个类型,用来去表示多个类型联合过后的一个结果

type StringOrNumber = string | number

const b:string | number = 100 //这个值类型只能是字符串或者数字
const b:StringOrNumber = 100 //这个类型的别名可以重复使用了

//maybe类型====================================

const gender:?number = 0 //需要此时变量为空,则在number前面加上?,表示这个变量除了可以接收number以外还可以接收null或者undefined
//相当于下面用法

const gender:number | null | void = undefined  

15. Mixed and any

/*
Mixed Any

@flow

*/

function passMixed(value:mixed){//mixed 类型实际上是所有类型的联合类型,可以理解成//string 或者 number 或者Boolean或者是其它任何一个类型

    value.substr(1)  //mixed是强类型,直接报语法错误,前面要加个类型判断if(typeof value === 'string)

    value*value //mixed是强类型,直接报语法错误if(typeof value === 'number')
}

passMixed('string')

passMixed(100)

//any跟mixed用法类似==========================================

function passAny(value:any){ //any 是弱类型,mixed仍然是强类型
    value.substr(1)  //可以把value当做任意类型使用,例如把它当做一个字符串,调用substr方法

    value*value //也可以当做一个数字,做乘法运算,语法上不会报错,并不是说运行阶段会报错,所以说any是弱类型
}

passAny('string')

passAny(100)

//尽量不要使用any,老代码和新代码可能要做到一个兼容,就用到any类型

Sixteen, flow summary

For more details, please visit https://www.saltycrane.com/cheat-sheets/flow-type/latest/

Guess you like

Origin blog.csdn.net/weixin_41962912/article/details/109837314