Flow (2) — simple syntax usage

Time:2021-2-22

catalog

  • Flow type inference
  • Where flow type annotations are used
  • Flow Type Annotations

    • Type reference website
    • Primitive type
    • Array type

      • Tuple types
    • object type

      • General writing
      • Add optional properties
      • Map class
      • Mixed use
    • Function type

    • Special types

      • Literal type
      • May type
    • Mixed and any

      • Mixed
      • Any
      • The difference between the two
  • Flow runtime API

I wrote it beforeFlowIf you want to review the reference flow (1) – Javascript static type checker, here is a brief introductionFlowUnderstand the grammar ofFlowThe meaning of is in the third-party source code can be seenFlowThe use of, can help us better understand the source code.

Flow type inference

There is no execution variable type, but the type can be inferred according to the usage of the code, which is called type inference

// @flow
//Because the string cannot be multiplied, an error will also be reported
 function square (n) {
   return n * n
 }

 square('100')

Flow (2) -- simple syntax usage

However, although there is type inference, it is recommended that developers add each type to make it readable.

Where flow type annotations are used

mostflowYou can infer variable types, but that doesn’t mean you don’t need to add type annotations to each variable. Adding type annotation can clearly restrict types, and it is very helpful for us to understand the code here later. It is recommended to use type annotation as much as possible

  • Where types can be labeled

    • Function parameters
    • variable
    • Function return value
// @flow
//Function Parameter annotation type annotation
function square (n: number) {
   return n * n
}

//Variable annotation type annotation
let num: number = 100

//Function return value annotation type annotation
function foo (): number {
   return 100
}
//In the above case, if there is no return value, undefind will be returned by default, and an error will also be reported
//So if there is no return value, you need to mark the return type as void
function foo1 (): void {
   
}

Flow Type Annotations

Type reference website

  • Flow website type annotations
  • Flow kitchen sheets third party type manual

Primitive type

// @flow

 //String
 const a: string = 'foobar'

 //Numbers
 const b1: number = 100
 const b2: number = NaN
 Const B3: number = infinity // Infinity

 //Boor
 const c1: boolean = true
 const c2: boolean = false

 // null
 const d: null = null

 // undefined
 const e: void = undefined

 // symbol
 const f: symbol = Symbol()

Array type

// @flow
//Writing method 1: after the array to add generic parameters, number specifies all the numbers of the array, if there are other types will report an error
 const arr1: Array<number> = [1, 2, 3]
 const arr2: Array<mixed> = [1, true, "three",{a:'1',b:2}]
//Writing method 2:
 const arr3: number[] = [1, 2, 3]

In addition to this array writing method, there is a special fixed length array, which is called tuple

Tuple types
  • Fixed length array. If the length is changed, an error will be reported
  • The element corresponding to the subscript must be of the specified type and must match when setting a new value
  • Tuple mismatchArrayType, because the length of the array type is uncertain
  • You can no longer use mutated arrays on tuples. For example:copyWithinfillpoppushreverseshiftsortspliceunshift
// @flow
//Tuple -- fixed length array
 //The following array specifies two elements. If the length is changed, an error will be reported, and the element corresponding to the subscript must be of the specified type
 const arr4: [string, number] = ['foo', 100]
 arr4[2] = 1 // Cannot assign `1` to `arr3[2]` because  tuple type [1] only has 2 elements, so index 2 is out of bounds.
 const item0: string = arr4[0] // Works!
 const item1: number = arr4[0] // Cannot assign `arr3[0]` to `item1` because  string [1] is incompatible with  number [2]

object type

General writing

Determine what key values are in an object and what type each is

// @flow
 const obj1: { foo: string, bar: number} = { foo: 'string', bar: 100}
 
//If you access properties that are not in obji1, you will return undefined. Now you will report an error as a type
 obj1.baz // Cannot get `obj1.baz` because property `baz` (did you mean `bar`?) is missing in  object type [1]
Add optional properties

Optional properties can beundefinedOr omit, but not benull

//If foo is optional, add a question mark after foo
 //Optional properties can be undefined or omitted, but cannot be null
 const obj2: { foo?: string, bar: number} = { bar: 100}
 obj2.foo = undefined // Works!
 obj2.foo = null // Cannot assign `null` to `obj2.foo` because  null [1] is incompatible with  string [2]
Map class

The type of the key is in square brackets

//If the initialization is empty, you can add your own key value pairs, specifying that the key is of string type and the value is also of string type
 const obj3: { [string] : string } = {}

 obj3.key1 = 'value1'
 obj3.key2 = 100 // annot assign `100` to `obj3.key2` because  number [1] is incompatible with  string [2]
Mixed use

MapClass and normal can be mixed

// @flow
var obj: {
  size: number,
  [id: number]: string
} = {
  size: 0
};

function add(id: number, name: string) {
  obj[id] = name;
  obj.size++;
}

Function type

It generally refers to type annotation of parameter type and return value type

Function parameters
// @flow

//Parameter input determines the type
 function square (n: number) {
   return n * n
 }
Optional function parameters
function func1 (num?: number) {
    const n = num ? num : 1
    console.log(n)
 }

 Func1() // 1 can accept undefined, not null
 func1(2) // 2
 func1(null) // Error!
Rest parameter
// @flow
function method(...args: Array<number>) {
  // ...
}

method();        // Works.
method(1);       // Works.
method(1, 2);    // Works.
method(1, 2, 3); // Works.
Function return
//The return value determines the type
 //There is a return value
 function foo (): number {
   return 100
 }
 //No return value
 function foo1 (): void {
   
 }

//Callback function parameters and return value types 
 function func (callback: (string, number) => void) {
   callback('string', 100)
 }

 func(function (str, n) {
   // str => string
   // n => number
   //No return value
 })

Special types

Literal type

Different from the traditional type, this literal type must restrict that the variable must be a certain value. Generally, it will not be used alone, but will cooperate with other typesUnion typeTo combine the values of several properties

// @flow
//The following defines the literal quantity of N. the value can only store foo strings, and cannot be changed into other strings or other types
const n: 'foo' = 'foo'
//It can only be one of the following three string types
const type : 'success' | 'warning' | 'danger' = 'success'
//B variable can be string or number, string or number
const b: string | number = 'string' // 100 


//You can also define a type by yourself. Stringornumber is the alias of a type
type StringOrNumber = string | number
const test: StringOrNumber = 'string' // 100
May type

It is possible to expand on the basic typesnullandundefinedTypes of

// @flow
//Add? Null and undefined can be used
const gender: ?number = null
const gender1: ?number = undefined
const gender2: ?number = 100

//Equal to number or null or undefined below
const gender: number | null | void = undefined

Mixed and any

Mixed

MixedCan receive any type of value, is a union type of all typesstring | number | boolean | ...

//The parameter is of type mixed
function passMixed (value: mixed) {
  console.log(value)
}

passMixed('string') // string
passMixed(100) // 100
Any

andMixedSimilarly, you can receive any type of value

function passAny (value: any) {
    console.log(value)
}

passAny('string') // string

passAny(100) // 100
The difference between the two
  • MixedIt is a strong type. If there is a hidden danger, it will report an error. It can only be usedtypeofMake type judgment
  • AnyIs a weak type, if there are hidden dangers, syntax will not report errors.
  • MixedIt is safe (recommended),AnyIt’s not safe. It’s meant to be compatible with old code
// Mixed
//If it is not clear whether the variable is a string or a number, it cannot be used directly and an error will be reported
function passMixed (value: mixed) {
  console.log(value)
  value = value ** 2 // Cannot perform arithmetic operation because  mixed [1] is not a number.
}

//If you want to solve the above problem, you need to use typeof for type judgment
function passMixed (value: mixed) {
  if (typeof value === 'string') {
    value.substr(1)
  }
  if (typeof value === 'number') {
    value ** 2
  }
}
// Any
//The following syntax will not report an error, and the runtime is uncertain
function passAny ( value: any) {
  value = value ** 2
}

Flow runtime API

JavaScriptNeed to run in an environment, such as browser environment ornodeEnvironmental Science.
They have their own ideasAPI, as in the browserDOMandBOMnodeInpathWait, we’re hereflowThese objects are also used in.

Then there are special type restrictions, such as:

document.getElementById () // if the parameter is passed to a string, an error will be reported
//These are some of the limitations of the built-in API in the browser environment
document.getElementById ('app ') // the return type is HtmlElement
//If the corresponding element is not found, the null type is also returned, which can be written when receiving
const element: HTMLElement | null = document.getElementById('app')

Right click to jump to the definition. You can see that there are definitions in the original

Flow (2) -- simple syntax usage

The official website warehouse gives some type statements, which can be used for reference when developing

  • Members of core JS standard library: object, array, math, JSON
  • dom
  • bom
  • cssom
  • node