Understand TypeScript Data Types
In the previous article
and
companion video of this series you prepared an ASP.NET Core project in
Visual Studio to use TypeScript. You also developed a simple "Hello World"
example. Now let's move ahead and learn something about the data types supported
by TypeScript.
One of the strengths of TypeScript is its strongly typed nature. Unlike plain
JavaScript where the data type of a variable is determined dynamically,
TypeScript allows you to declare a variable with a specific data type. Some data
types that are commonly used include string, number, boolean, any, and object.
You can see the complete list of supported data types
here. Rather than simply enumerating through the available data types I am
going to develop a simple Temperature Convertor that allows you to convert
temperature values between Celsius and Fahrenheit. While developing this example
you will be introduced with a few basic data types supported by TypeScript along
with the associated keywords and syntax.
The Temperature Convertor application that you build here looks like this:
As you can see, there is a textbox for entering a temperature value. There
are two buttons - Convert to Celsius and Convert to Fahrenheit that perform the
respective conversion. The result of conversion is displayed below the buttons.
A date-time stamp is also rendered at the bottom.
Begin by opening the same project that you created in the previous part of
this series. Then add two files to the TypeScript folder using Add New Item
dialog - DataTypes.ts and DataTypes.html.
Then open DataTypes.ts file and define an enumeration named ConversionType:
enum ConversionType {
CelsiusToFahrenheit,
FahrenheitToCelsius
}
As a C# developer you are already familiar with enumerations. TypeScript
enumerations server the same purpose. The ConversionType enumeration is defined
using enum keyword and contains two values - CelsiusToFahrenheit and
FahrenheitToCelsius. Enumerations are basically numeric values and here they are
0 and 1 respectively. You could have also explicitly assigned numeric values to
them.
Next, you will write a function called convert(). The convert() function is
intended to convert a temperature value from one measuring unit to another and
its signature looks like this:
function convert(value: number,
conversionType: ConversionType) {
}
Notice the function signature carefully. The convert() function takes two
parameters, value and type. You can indicate data type of the parameter using
colon (:) syntax. So, value parameter is of type number and type parameter is of
type ConversionType.
Inside, you will declare a few variables and constants. The following code
shows them:
let tempInC: number;
let tempInF: number;
let message: string;
const timeStamp: Date = new Date();
const clearValue: boolean = true;
In order to declare a variable you use let keyword. If you used JavaScript
before you are probably familiar with declaring variables using var keyword.
Although you can still use var keyword in TypeScript, modern JavaScript has
introduced the let keyword that does the job. The main difference between var
and let is - a variable declared with var has scope of that function whereas a
variable declared using let has scope of a block. You can read more about var
and let
here and
here.
So, the above code declares tempInC, tempInF, and
message. A variable's data type is specified after the colon (:). For example,
data type of tempInC and tempInF is number. The code also declares two constants
timeStamp and clearValue. The timeStamp constant holds the current date-time
value and is used to display time-stamp on the page. The clearValue constant
holds a boolean value of true and it indicates whether the textbox should be
cleared upon converting a temperature value. Since both of them are constants,
their values need to be assigned while declaring them.
Next, you need to perform the conversion between Celsius and Fahrenheit
depending on the ConversionType value passed in the convert() function. The code
that does this conversion is discussed below:
if (conversionType == ConversionType.CelsiusToFahrenheit) {
tempInC = value;
tempInF = tempInC * 9 / 5 + 32;
message = tempInC + "\xB0C = " + tempInF + " \xB0F";
}
if (conversionType == ConversionType.FahrenheitToCelsius) {
tempInF = value;
tempInC = (tempInF - 32) * 5 / 9;
message = tempInF + "\xB0F = " + tempInC + " \xB0C";
}
The if statement that follows checks whether the temperature is to be
converted from Celsius to Fahrenheit. If so, the temperature value is stored in
tempInC variable. The next line converts the temperature into Fahrenheit
equivalent using a mathematical formula and stores the result into tempInF
variable. Then the message variable is assigned a message string by
concatenating tempInC and tempInF values.
The second if statement is quite similar but converts a temperature value
from Fahrenheit to Celsius.
The final piece of code outputs the values of message and timeStamp on the
page. This code is shown below:
document.getElementById("msg").innerHTML
= "<h2>Result : " + message + "</h2>";
document.getElementById("stamp").innerHTML
= "<h3>Calculated on : " +
timeStamp.toISOString() + "</h3>";
if (clearValue) {
let tempValue: HTMLInputElement;
tempValue = <HTMLInputElement>document
.getElementById("tempValue");
tempValue.value = "";
}
The first line of this code grabs a DOM element whose ID is msg. and sets its
innerHTML property to a message. The next line renders the date-time stamp in a
DOM element with ID of stamp. The if statement that follows checks the
clearValue constant and if it is true empties the textbox. Notice the type
casting syntax of TypeScript used there. The getEmelemnyById() method returns
HTMLElement whereas a textbox (<input> element) is represented by
HTMLInputElement. So, type conversion is necessary. After obtaining a reference
to HTMLInputElement, its value property is assigned an empty string.
This completes the convert() function. For the sake of clarity the complete
convert() function is given below:
function convert(value: number,
conversionType: ConversionType) {
let tempInC: number;
let tempInF: number;
let message: string;
const timeStamp: Date = new Date();
const clearValue: boolean = true;
if (conversionType ==
ConversionType.CelsiusToFahrenheit) {
tempInC = value;
tempInF = tempInC * 9 / 5 + 32;
message = tempInC + "\xB0C = "
+ tempInF + " \xB0F";
}
if (conversionType ==
ConversionType.FahrenheitToCelsius) {
tempInF = value;
tempInC = (tempInF - 32) * 5 / 9;
message = tempInF + "\xB0C = "
+ tempInC + " \xB0F";
}
document.getElementById("msg").innerHTML
= "<h2>Result : " + message + "</h2>";
document.getElementById("stamp").innerHTML
= "<h3>Calculated on : " + timeStamp.toISOString()
+ "</h3>";
if (clearValue) {
let tempValue: HTMLInputElement;
tempValue = <HTMLInputElement>document.
getElementById("tempValue");
tempValue.value = "";
}
}
You need to write two more functions that get called when the "Convert to
Celsius" and "Convert to Fahrenheit" buttons are clicked. These functions are
shown next:
function convertToCelsius() {
let value: number;
let tempValue: HTMLInputElement;
tempValue = <HTMLInputElement>
document.getElementById("tempValue");
value = parseInt(tempValue.value);
convert(value, ConversionType.FahrenheitToCelsius);
}
function convertToFahrenheit() {
let value: number;
let tempValue: HTMLInputElement;
tempValue = <HTMLInputElement>
document.getElementById("tempValue");
value = parseInt(tempValue.value);
convert(value, ConversionType.CelsiusToFahrenheit);
}
The convertToCelsius() function converts a value entered into the textbox
into Celsius equivalent. Inside, the code grabs the value from the textbox and
stores it in value variable. Notice the use of parseInt() to convert a string
value into an integer. Then the code calls the convert() function created
earlier. The value and ConversionType of FahrenheitToCelsius is passed to the
convert() function.
The convertToFahrenheit() function is similar but calls the convert()
function by passing ConversionType.CelsiusToFahrenheit.
This completes DataTypes.ts. If you save the file or build the project you
should get DataTypes.js output file under the Output folder.
Now let's proceed further and add some markup in the DataTypes.html file. The
following markup shows the important pieces from the DataTypes.html.
<h1>Temperature Converter</h1>
<table cellpadding="10">
<tr>
<td>Temperature Value : </td>
<td><input id="tempValue" type="text" /></td>
</tr>
<tr>
<td colspan="2">
<button onclick="convertToCelsius()">
Convert to Celsius</button>
<button onclick="convertToFahrenheit()">
Convert to Fahrenheit</button>
</td>
</tr>
</table>
<div id="msg"></div>
<div id="stamp"></div>
<script src="/TypeScript/Output/DataTypes.js"></script>
As you can see, there is an <input> element with ID tempValue. There are two
<button> elements that trigger convertToCelsius() and convertToFahrenheit()
functions when clicked.
The two <div> elements msg and stamp are used to display message and
date-time stamp respectively (see earlier code).
Finally, the <script> tag points to the DateTypes.js file.
Save all your work and open DataTypes.html in the browser. Enter some value
in the textbox and click on one of the buttons. Confirm whether the conversion
is happening as expected.
That's it for now! Keep coding!!