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 ]