vue源码学习 --- flow(5)
原文地址: https://flow.org/en/docs/types/arrays/#toc-array-type-shorthand-syntax
一. Array
- 基本使用
- 只读数组
1. 基本使用
Array access is unsafe
When you retrieve an element from an array there is always a possibility that it is undefined.
You could have either accessed an index which is out of the bounds of the array,
or the element could not exist because it is a “sparse array”.
(当你检索一个数组的元素的时候,总是有可能得到一个undefined的. 你可能会用下标检索一个超出数组长度的元素, 也可能会访问一个数组中不存在的元素)
然而,
As Flow is made to be smarter it may be possible in the future to fix this problem, but for now you should be aware of it.
let arr: Array<number> = [1, 2, 3];
let arr: Array<mixed> = [1, true, 'three', null, undefined];
let arr: number[] = [0, 1, 2, 3];
let arr1: ?number[] = null; // Works!
let arr4: ?number[] = undefined; // Works!
let arr2: ?number[] = [1, 2]; // Works!
let arr3: (?number)[] = [1, null, undefined]; // Works!
$ReadOnlyArray<T> 只读数组
it is the supertype of all arrays and all tuples and represents a read-only view of an array(是arrays和tuples的父类)
// let readonlyArray: $ReadOnlyArray<number> = [1, 2, 3],
// let first = readonlyArray[0] // OK to read
// readonlyArray[1] = 20 // Error!
// readonlyArray.push(4) // Error!
// 类似于const声明的变量不能被改变,但是能改变const声明的对象的属性值, $ReadOnlyArray<T>也是可以修改数组中对象的属性值的
let readonlyArray2: $ReadOnlyArray<{x: number}> = [{x: 1}];
// readonlyArray2[0] = {x: 42}; // Error!
// readonlyArray2[0].x = 42; // OK
二.Tuple
(1) 元组类型在JavaScript中并不存在,在flow中存在.
(2) 元组有严格的长度限制,不同长度的元组不能相等. 因此,数组和元组不能相同
(3) 元组只能使用Array.prototype上的一个方法: join
let tuple3: [number, boolean, string] = [1, true, "three"];
// 取值超过元组长度, 会返回void(undefined)
// let val: void = tuple3[3]; // Error!
tuple3[0] = 2; // Works!
tuple3[1] = false; // Works!
tuple3[2] = "foo"; // Works!
// tuple3[0] = "bar"; // Error!
let tuple1: [number, boolean] = [1, true];
// let tuple2: [number, boolean, void] = tuple1; // Error!
let array: Array<number> = [1, 2];
// let tuple: [number, number] = array; // Error!
let tuple: [number, number] = [1, 2];
tuple.join(', '); // Works!
vue源码学习 --- flow(6)
https://www.jianshu.com/p/7ebb99589589