ts一个元组既有数字也有字符串该怎么表示?

const hello : [number, string] = [1, '2', '2', 1]
console.log(hello)

这个虽然可以实现,但是却固定了顺序,假如一个元组既有数字也有字符串顺序和长度也不确定该如何表示?

const a: [number, string, number, string] = [1,'2',3, '4']
const getHello = () => {
    let b = []
    for (let i = 0; i < Math.floor(Math.random()*6); i++) {
        b.push(a[Math.floor(Math.random()*4)])
    }
    return b
}

console.log(getHello())
阅读 3.7k
3 个回答

顺序和长度都不固定那叫啥元组(Tuple)?那不就是数组(Array)么?

看官方定义:

Tuple types allow you to express an array with a fixed number of elements whose types are known, but need not be the same. For example, you may want to represent a value as a pair of a string and a number:

type ArrayA = Array<string | number>

const a: [number|string, number|string,number|string,number|string] = ['1','2',3, '4']
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进