• typescript元组


    元组

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

    元组起源于函数编程语言(如F#),这些语言中会频繁使用元组

    简单例子

    定义一对值分别为stringnumber的元组

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

    当赋值活访问一个已知索引的元素时,会得到正确的类型

    let t: [string, number] = ['tom', 25]
      t[0].slice(1)
      t[1].toFixed(2)
      console.log(t)
    

    也可以只赋值其中一项

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

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

    let tom:[string,number]
    tom = ['tom', 123]
    
    let tom :[string,number]
    tom = ['tom'] //Property '1' is missing in type '[string]' but required in type '[string, number]'.
    

    越界的元素

    当添加越界元素时,它的类型会被限制为元组中每个类型的联合类型

    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'.
    
  • 相关阅读:
    B-树和B+树的应用:数据搜索和数据库索引【转】
    与网络编程相关的信号:
    Reactor构架模式
    EINTR错误
    通讯链路的检测方法
    背景减法——自组织算法
    数据结构7_链二叉树
    背景减法——Vibe
    操作系统2_进程控制
    操作系统1_进程控制块PCB
  • 原文地址:https://www.cnblogs.com/dehenliu/p/16077004.html
Copyright © 2020-2023  润新知