TypeScript:元组示例
在 TypeScript 中,元组是一种特定类型的数组,具有以下特征:
- 元素的数量和顺序是固定的,必须遵守
- 每个元素的类型都是预定义且严格的
例子:
// define tuple
let myTuple: [string, number, boolean, Array<String>];
// initialize value
myTuple = ['hello', 1, true, ['a', 'b', 'c']];
另一个例子:
// define type
type MyTuple = [number, string, boolean];
// define function that takes a tuple as argument and returns the modified tuple
const myFunction = (arg1: MyTuple): MyTuple => {
return [arg1[0] ** 3, arg1[1].replace(' ', '-'), !arg1[2]];
};
// try it
const result = myFunction([10, 'welcome to KindaCode.com', true]);
console.log(result);
输出:
[ 1000, 'welcome-to KindaCode.com', false ]
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布,任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站。本站所有源码与软件均为原作者提供,仅供学习和研究使用。如您对本站的相关版权有任何异议,或者认为侵犯了您的合法权益,请及时通知我们处理。