欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

TypeScript之元組、數(shù)組及as?const的使用

 更新時間:2023年10月27日 11:15:32   作者:程序員啊楠  
TypeScript中的元組、數(shù)組和as?const關(guān)鍵字對于類型安全性和代碼可讀性非常重要,本文主要介紹了TypeScript之元組、數(shù)組及as?const的使用,感興趣的可以了解一下

一、元組 && 數(shù)組

在 TS 中,元組表示 這個數(shù)組有不同的類型 。簡單的一句話來表述,如果類型相同的一組數(shù)據(jù)就是數(shù)組,反之就是元組;數(shù)組的 api 對于元組來講也是通用的(push、pop等),只是類型不同;

1、數(shù)組的定義

//定義數(shù)組的方式
let arr: number[] = [1, 2, 3]; //第一種: 必須全部是number類型;

let arr2: Array<number> = [1, 2, 3]; // 第二種

let arr3: Array<number> = new Array(4); // 第三種:表示定義一個數(shù)組的長度,一般固定一個數(shù)組的長度時這個方法比較方便
let arr4 = new Array<number>(4);  //這種寫法和 arr3 效果是一樣的
console.log(arr3.length);

// interface 定義
interface NumberArray {
    [index: number]: number;
}

let arr5: NumberArray = [1, 2, 3];

//類數(shù)組
function sum() {
    let args: IArguments = arguments;

    // args.callee()
}

2、元組的定義

// 類型固定的元組
// let arrAny: any[] = [1, 'TEST']; 奇葩且沒有意義的寫法,不推薦
let tuple1: [number, string, boolean] = [1, 'TEST', false];

// 數(shù)組和元組的區(qū)別
// 利用函數(shù)動態(tài)拼合一個元組
function useFetch() {
    const response: string = "Barry";
    const age: number = 25;
    return [response, age] as const;
}
// 這里如果不使用 as const 會發(fā)現(xiàn) 我們結(jié)構(gòu)出來的數(shù)組類型是response: string | number
// 使用完 as const 以后 為string,as const 也叫類型斷言
const [response] = useFetch() // 發(fā)現(xiàn) const response: string | number

// 數(shù)組轉(zhuǎn)化元組 泛型
function useFetch2() {
    const response: string = "Barry";
    const age: number = 25;
    return tuplify(response, age)
}

function tuplify<T extends unknown[]>(...elements: T): T {
    return elements;

}

三、as  const

1.不強制類型轉(zhuǎn)換

as const 被稱為 const 類型斷言,const 類型斷言告訴編譯器,要將這個表達式推斷為最具體的類型,如果不使用它的話,編譯器會使用默認(rèn)的類型推斷行為,可能會把表達式推斷為更通用的類型。

注意這里 const 是類型斷言,不是強制轉(zhuǎn)換,在 typescript 中,const 類型斷言,會從編譯后的 JavaScript 中完全刪除,所以使用或者不使用 as const 的應(yīng)用程序,在運行時完全沒有區(qū)別。

所以 as const 只是讓編譯器更好的了解代碼的意圖,讓它更加精確的區(qū)分正確和錯誤的代碼。

stack overflow : What does the "as const" mean in TypeScript and what is its use case?

https://stackoverflow.com/questions/66993264/what-does-the-as-const-mean-in-typescript-and-what-is-its-use-case

2.強制類型轉(zhuǎn)換

// 強制類型轉(zhuǎn)換

function getLength(str: string | number): number {
    // if((<String>str).length) 上下兩種方式
    if ((str as string).length) {
        return (<String>str).length
    } else {
        return str.toString().length;
    }
}

3.類型別名

// 類型別名

type Name = string;
type NameResolver = () => string;
type NameOrResolver = Name | NameResolver;
function getName(n: NameOrResolver): Name {
    if (typeof n === 'string') {
        return n
    }
}

// interface  實現(xiàn) 類型

interface A {

}
function helper(options: A): A {
    return options
}

到此這篇關(guān)于TypeScript之元組、數(shù)組以及as const的文章就介紹到這了,更多相關(guān)TypeScript 元組、數(shù)組以及as const內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論