vue源碼學(xué)習(xí) --- flow(5)

原文地址: https://flow.org/en/docs/types/arrays/#toc-array-type-shorthand-syntax

一. Array

  1. 基本使用
  2. 只讀數(shù)組

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”.
(當(dāng)你檢索一個數(shù)組的元素的時候,總是有可能得到一個undefined的. 你可能會用下標(biāo)檢索一個超出數(shù)組長度的元素, 也可能會訪問一個數(shù)組中不存在的元素)
然而,
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> 只讀數(shù)組
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>也是可以修改數(shù)組中對象的屬性值的
let readonlyArray2: $ReadOnlyArray<{x: number}> = [{x: 1}];
// readonlyArray2[0] = {x: 42}; // Error!
// readonlyArray2[0].x = 42; // OK

二.Tuple

(1) 元組類型在JavaScript中并不存在,在flow中存在.
(2) 元組有嚴(yán)格的長度限制,不同長度的元組不能相等. 因此,數(shù)組和元組不能相同
(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源碼學(xué)習(xí) --- flow(6)
http://www.itdecent.cn/p/7ebb99589589

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容