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

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.
主站蜘蛛池模板: 林州市| 昭觉县| 鄂温| 洛南县| 宝兴县| 若尔盖县| 大余县| 毕节市| 娄底市| 江西省| 上高县| 金寨县| 天津市| 革吉县| 龙山县| 河北区| 陆丰市| 张家港市| 仙桃市| 嘉兴市| 潞西市| 德清县| 探索| 碌曲县| 渝中区| 金堂县| 修武县| 罗源县| 南澳县| 黑河市| 永宁县| 鹰潭市| 房山区| 湘潭县| 双峰县| 玉溪市| 大荔县| 苗栗县| 花莲县| 松阳县| 玉溪市|