gpt4 book ai didi

typescript - 如何检查变量是否是 TypeScript 中的元组

转载 作者:行者123 更新时间:2023-12-02 00:52:11 25 4
gpt4 key购买 nike

我正在尝试查看传递给函数的变量(可以是数字数组或元组数组)是否是元组数组。

function (times: Array<number> | Array<[number, number]>) {
if (times[0] instanceof [number, number]) {
console.log("Its the tuple one!");
}
}

虽然上面的代码不起作用,但我也尝试了 if (times[0] instanceof tuple)) 但这也不起作用。如何做到这一点?

谢谢!

最佳答案

根据Basic Types > Tuple文档:

Tuple types allow you to express an array where the type of a fixed number of elements is known, but need not be the same.

意味着元组只是数组。
此外,由于 typescript 编译为 javascript,而 javascript 没有元组,因此在运行时检查类型意味着您需要检查 javascript 类型,而不是在运行时不存在的 ts 类型。

回答你的问题:

function fn(times: Array<number> | Array<[number, number]>) {
if (times[0] instanceof Array) {
console.log("Its the tuple one!");
}
}

关于typescript - 如何检查变量是否是 TypeScript 中的元组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38858106/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com