官术网_书友最值得收藏!

Creating a tuple

A tuple is like an organized typed array. Let's create one to see how it works:

  1. Inside the chapter-02 folder, create a file called tuple.ts, and add the following code:
const organizedArray: [number, string, boolean] = [0, 'text',
false];
let myArray: [number, string, boolean];
myArray = ['text', 0, false]
console.log(myArray);

The preceding code looks fine for JavaScript, but in TypeScript, we must respect the variable type; here, we are trying to pass a string where we must pass a number.

  1. In your Terminal, type the following command:
tsc tuple.ts

You will see the following error message:

tuple.ts(4,1): error TS2322: Type '[string, number, false]' is not assignable to type '[number, string, boolean]'.
Type 'string' is not assignable to type 'number'.
In VS Code, you will see the error message before you compile your file. This is a very helpful feature.

When we fix it with the right order (myArray = [0, 'text', false]), the error message disappears.

It's also possible to create a tuple type and use it to assign a variable, as we can see in the next example.

  1. Go back to your Terminal and add the following code to the tuple.ts file:
// using tuple as Type
type Tuple = [number, string, boolean];
let myTuple: Tuple;
myTuple = [0, 'text', false];
console.log(myTuple);

At this point, you may be wondering why the previous examples have a console.log output.

With the help of Node.js, which we installed previously, we can run the examples and view the output of the console.log() function.

  1. Inside the Terminal, type the following command:
node tuple.js
Note that you will need to run the JavaScript version, as in the previous example. If you try to run the TypeScript file directly, you will probably receive an error message.
主站蜘蛛池模板: 唐海县| 新民市| 长宁县| 衡南县| 福安市| 苗栗市| 榆林市| 新蔡县| 马边| 蒲江县| 辽源市| 西峡县| 南平市| 阳朔县| 铜梁县| 普兰店市| 正阳县| 无锡市| 宜宾县| 汝阳县| 嘉善县| 张北县| 无棣县| 博湖县| 昌图县| 盐山县| 武冈市| 涞源县| 漳浦县| 珲春市| 信丰县| 建宁县| 莱西市| 衡阳县| 永嘉县| 昭平县| 沾益县| 海南省| 岗巴县| 镇安县| 乾安县|