TypeScript之元组、数组以及 as const

一、元组 && 数组

在 TS 中,元组表示 这个数组有不同的类型 。简单的一句话来表述,如果类型相同的一组数据就是数组,反之就是元组;数组的 api 对于元组来讲也是通用的(push、pop等),只是类型不同;

1、数组的定义

//定义数组的方式
let arr: number[] = [1, 2, 3]; //第一种: 必须全部是number类型;

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

let arr3: Array<number> = new Array(4); // 第三种:表示定义一个数组的长度,一般固定一个数组的长度时这个方法比较方便
let arr4 = new Array<number>(4);  //这种写法和 arr3 效果是一样的
console.log(arr3.length);

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

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

//类数组
function sum() {
    let args: IArguments = arguments;

    // args.callee()
}

2、元组的定义

// 类型固定的元组
// let arrAny: any[] = [1, 'TEST']; 奇葩且没有意义的写法,不推荐
let tuple1: [number, string, boolean] = [1, 'TEST', false];

// 数组和元组的区别
// 利用函数动态拼合一个元组
function useFetch() {
    const response: string = "Barry";
    const age: number = 25;
    return [response, age] as const;
}
// 这里如果不使用 as const 会发现 我们结构出来的数组类型是response: string | number
// 使用完 as const 以后 为string,as const 也叫类型断言
const [response] = useFetch() // 发现 const response: string | number

// 数组转化元组 泛型
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.不强制类型转换

as const 被称为 const 类型断言,const 类型断言告诉编译器,要将这个表达式推断为最具体的类型,如果不使用它的话,编译器会使用默认的类型推断行为,可能会把表达式推断为更通用的类型。

注意这里 const 是类型断言,不是强制转换,在 typescript 中,const 类型断言,会从编译后的 JavaScript 中完全删除,所以使用或者不使用 as const 的应用程序,在运行时完全没有区别。

所以 as const 只是让编译器更好的了解代码的意图,让它更加精确的区分正确和错误的代码。

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.强制类型转换

// 强制类型转换

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  实现 类型

interface A {

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

猜你喜欢

转载自blog.csdn.net/weixin_56650035/article/details/122548173
今日推荐