- TypeScript Blueprints
- Ivo Gabe de Wolff
- 782字
- 2021-07-14 10:59:27
Quick example
The following example code shows some basic TypeScript usage. If you understand this code, you have enough knowledge for the next chapters. This example code creates an input box in which you can enter a name. When you click on the button, you will see a personalized greeting:
class Hello { private element: HTMLDivElement; private elementInput: HTMLInputElement; private elementText: HTMLDivElement; constructor(defaultName: string) { this.element = document.createElement("div"); this.elementInput = document.createElement("input"); this.elementText = document.createElement("div"); const elementButton = document.createElement("button"); elementButton.textContent = "Greet"; this.element.appendChild(this.elementInput); this.element.appendChild(elementButton); this.element.appendChild(this.elementText); this.elementInput.value = defaultName; this.greet(); elementButton.addEventListener("click", () => this.greet() ); } show(parent: HTMLElement) { parent.appendChild(this.element); } greet() { this.elementText.textContent = `Hello, ${ this.elementInput.value }!`; } } const hello = new Hello("World"); hello.show(document.body);
Tip
Downloading the example code
You can download the example code files for this book from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.
You can download the code files by following these steps:
- Log in or register to our website using your e-mail address and password.
- Hover the mouse pointer on the SUPPORT tab at the top.
- Click on Code Downloads & Errata.
- Enter the name of the book in the Search box.
- Select the book for which you're looking to download the code files.
- Choose from the drop-down menu where you purchased this book from.
- Click on Code Download.
You can also download the code files by clicking on the Code Files button on the book's web page at the Packt Publishing website. This page can be accessed by entering the book's name in the Search box. Please note that you need to be logged in to your Packt account.
Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:
- WinRAR / 7-Zip for Windows
- Zipeg / iZip / UnRarX for Mac
- 7-Zip / PeaZip for Linux
The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/TypeScript_Blueprints. We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!
The preceding code creates a class, Hello
. The class has three properties that contain an HTML element. We create these elements in the constructor. TypeScript has different types for all HTML elements and document.createElement
gives the corresponding element type. If you replace div
with span
(on the first line of the constructor), you would get a type error saying that type HTMLSpanElement
is not assignable to type HTMLDivElement
. The class has two functions: one to add the element to the HTML page and one to update the greeting based on the entered name.
It is not necessary to specify types for all variables. The types of the variables elementButton
and hello
can be inferred by the compiler.
You can see this example in action by creating a new directory and saving the file as scripts.ts
. In index.html
, you must add the following code:
<!DOCTYPE HTML> <html> <head> <title>Hello World</title> </head> <body> <script src="scripts.js"></script> </body> </html>
The TypeScript compiler runs on NodeJS, which can be installed from https://nodejs.org. Afterward, you can install the TypeScript compiler by running npm install typescript -g
in a console/terminal. You can compile the source file by running tsc scripts.ts
. This will create the scripts.js
file. Open index.html
in a browser to see the result.
The next sections explain the basics of TypeScript in more detail. After reading those sections, you should understand this example fully.
Transpiling
The compiler transpiles TypeScript to JavaScript. It does the following transformations on your source code:
- Remove all type annotations
- Compile new JavaScript features for old versions of JavaScript
- Compile TypeScript features that are not standard JavaScript
We can see the preceding three transformations in action in the next example:
enum Direction { Left, Right, Up, Down } let x: Direction = Direction.Left;
TypeScript compiles this to the following:
var Direction; (function (Direction) { Direction[Direction["Left"] = 0] = "Left"; Direction[Direction["Right"] = 1] = "Right"; Direction[Direction["Up"] = 2] = "Up"; Direction[Direction["Down"] = 3] = "Down"; })(Direction || (Direction = {})); var x = Direction.Left;
In the last line, you can see that the type annotation was removed. You can also see that let
was replaced by var
, since let
is not supported in older versions of JavaScript. The enum
declaration, which is not standard JavaScript, was transpiled to normal JavaScript.
Type checking
The most important feature of TypeScript is type checking. For instance, for the following code, it will report that you cannot assign a number to a string:
let x: string = 4;
In the next sections, you will learn the new features of the latest JavaScript versions. Afterward, we will discuss the basics of the type checker.
- Python快樂編程:人工智能深度學(xué)習(xí)基礎(chǔ)
- Git Version Control Cookbook
- Game Programming Using Qt Beginner's Guide
- AWS Serverless架構(gòu):使用AWS從傳統(tǒng)部署方式向Serverless架構(gòu)遷移
- Mastering Julia
- Scratch 3.0少兒編程與邏輯思維訓(xùn)練
- 零基礎(chǔ)學(xué)MQL:基于EA的自動化交易編程
- Oracle Database 12c Security Cookbook
- The DevOps 2.4 Toolkit
- Oracle BAM 11gR1 Handbook
- 蘋果的產(chǎn)品設(shè)計之道:創(chuàng)建優(yōu)秀產(chǎn)品、服務(wù)和用戶體驗的七個原則
- Test-Driven Machine Learning
- Visualforce Developer’s guide
- Python 3.7從入門到精通(視頻教學(xué)版)
- SQL Server 入門很輕松(微課超值版)