- Hands-On Full Stack Web Development with Angular 6 and Laravel 5
- Fernando Monteiro
- 296字
- 2021-07-23 19:18:49
Creating a tuple
A tuple is like an organized typed array. Let's create one to see how it works:
- 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.
- 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.
- 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.
- 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.
推薦閱讀
- 網絡協議工程
- 智能網聯汽車V2X與智能網聯設施I2X
- Spring Boot 2.0 Projects
- Hands-On Chatbot Development with Alexa Skills and Amazon Lex
- Learning Karaf Cellar
- PLC、現場總線及工業網絡實用技術速成
- Microsoft Dynamics CRM 2011 Applications(MB2-868) Certification Guide
- 網絡基礎與網絡管理項目化教程
- CCNP TSHOOT(642-832)認證考試指南
- Getting Started with nopCommerce
- 深入理解計算機網絡
- 物聯網
- 小型局域網組建
- 移動互聯網環境下的核心網剖析及演進
- Hands-On Cloud:Native Microservices with Jakarta EE