元组

1.定义

元组(Tuple)合并了不同类型的对象。

2.使用

let tom: [string, number];
tom[0] = 'Tom';
tom[1] = 25;

tom[0].slice(1);
tom[1].toFixed(2);

3.注意事项

  • 当直接对元组类型的变量进行初始化或者赋值的时候,需要提供所有元组类型中指定的项。

    let tom: [string, number];
    tom = ['Tom', 25];  
  • 当添加越界的元素时,它的类型会被限制为元组中每个类型的联合类型
    let tom: [string, number];
    tom = ['Tom', 25];
    tom.push('male');
    tom.push(true);
    // Argument of type 'true' is not assignable to parameter of type 'string | number'.

4.元组和数组的区别

在ts中,元组类型就是在定义数组的时候,类型和数据的个数一开始就已经限定好了。
元组类型的语法 :let arr : [ string ,number,boolean ] = [ ‘东方不败’ , 100 , true ]

备注:使用元组类型时,需要注意的是,元组类型在使用的时候,数据的类型的位置和数据的个数,需要和 在定义元组的时候的数据类型和位置相一致,不一致则会报错提示

 

posted @ 2023-08-22 18:48  李翠花xixi  阅读(34)  评论(0)    收藏  举报