20
Jumping into TypeScript

Angular is built on TypeScript, so it is important that you have an understanding of it in order to use Angular. This chapter will help you understand the fundamentals of TypeScript.

This chapter will familiarize you with the additions TypeScript gives to JavaScript. If you are familiar with C# and object-oriented programming, TypeScript will seem more familiar than JavaScript. This chapter will also familiarize you with the basics of programming in TypeScript; it discusses types, interfaces, classes, modules, functions, and generics. It is not intended to be a full language guide; rather, it is a primer on the language to help prepare you for using Angular.

Learning the Different Types

Like JavaScript, TypeScript uses data types to handle data, but there are some differences in syntax. TypeScript also adds in an extra type enumeration. The following list goes over the types and variables and their syntax for TypeScript:

Images String: This data type stores character data as a string. The character data is specified by either single or double quotation marks. All the data contained in the quotes will be assigned to the string variable. Consider these examples:
var myString: string = 'Some Text';
var anotherString: string = "Some More Text";

Images Number: This data type stores data as a numeric value. Numbers are useful in counting, calculations, and comparisons. Here are some examples:
var myInteger: number = 1;
var cost: number = 1.33;

Images Boolean: This data type stores a single bit that is either true or false. Booleans are often used for flags. For example, you might set a variable to false at the beginning of some code and then check it on completion to see if the code execution hit a certain spot. The following examples define true and false variables:
var yes: boolean = true;
var no: boolean = false;

Images Array: An indexed array is a series of separate distinct data items, all stored under a single variable name. Items in the array can be accessed by their zero-based index, using array[index]. The following are two examples of creating a simple array and then accessing the first element, which is at index 0:
var arr:string[] = ["one", "two", "three"];
var firstInArr = arr[0];
var arr2:Array<number> = ["a", "second", "array"];
var firstInArr2 = arr[0];

Images Null: Sometimes you do not have a value to store in a variable, either because it hasn’t been created or you are no longer using it. At such a time, you can set a variable to null. Using null is better than assigning a value of 0 or an empty string ("") because those may be valid values for the variable. By assigning null to a variable, you can assign no value and check against null inside your code, like this:
var newVar = null;

Images Any: In TypeScript you may not always know what type of variable you will be getting or using. In such a case, you can assign the variable type as any to allow any other type to be assigned to a variable. The following is an example of assigning multiple types to the same variable:
Var anyType: any = "String Assigned";
Var anyType = 404;
Var anyType = True;

Images Void: You use void when you don’t want a variable to have any type at all. In TypeScript, using void prohibits you from assigning or returning a value. In most cases you use void when declaring a function you don’t want to have a return value. The following example is a function of type void:
function empty(): void { document.write("code goes here"); }

Images Enum: TypeScript lets us use enum, which allows you to give names to enumerated values. The following is the syntax to declare enum:
Enum People {Bob, John, Alex}

Also, to reference the values in enum, you use this syntax:
var x = People.Bob

or this:
var y = People[0]

By using this syntax, you set var x equal to the number 0 and var y equal to the string Bob.

Understanding Interfaces

Interfaces are a fundamental part of TypeScript. They allow you to have a set structure for an application. They are powerful tools that allow you to set structures for objects, functions, arrays, and classes. You can think of interfaces as defining standards you want your interface subsets to follow.

To define an interface in TypeScript, you use the keyword interface followed by the structure you want your objects to follow, like this:

interface Person {
     hairColor: string;
     age: number;
}

You can also add optional items to interfaces to allow some flexibility within a program. You do this by using the syntax attribute?: Boolean;, as shown in the following examples:

interface Person {
    hairColor: string;
    age: number;
    alive?: Boolean;
}

You can define an interface for functions in TypeScript. This helps ensure that functions take in specific types of parameters. The following example sets var z equal to variables x + y, using an instance of the interface AddNums:

interface AddNums {
    (num1: number, num2: number)
}
var x: number = 5;
var y: number = 10;
 
var newNum: AddNums;
newNum = function(num1: number, num2: number){
    var result: number = num1 + num2;
    document.write(result)
    return result;
}
 
var z = newNum(x, y);

Interfaces also allow you to define how you would like arrays to look. You give arrays the index type to define the types allowed for an object’s index. You then give the return type for the index. Here is an example:

interface Stringy {
    [index: number]: string;
}
var coolArray: Stringy;
coolArray = ["Apples", "Bananas"];

Finally, interfaces allow you to define class structures. As with a function interface, this allows you to set required variables and methods within each class. It’s important to note that this only describes the public portion of a class and not a private section. (We talk more about classes in the next section.) In this example, the interface has a property called name and a method called feed:

interface PersonInterface {
    name: string;
    feed();
}

Implementing Classes

JavaScript is a language that is based on prototype inheritance. Thanks to ECMAScript 6 (ES6) and TypeScript, you can use class-based programming. You can describe the objects you put into a program by using the base attributes to describe classes.

To define a class in TypeScript, you use the syntax class ClassName{ code goes here }. The following example defines a simple class that defines a Person object with a feed function:

class Person {
    name: string;
    age: number;
    hungry: boolean = true;
    constructor(name: string, age?: number) {
        this.name = name;
        this.age = age;
    }
    feed() {
        this.hungry = false;
        return "Yummy!";
    }
}
var Brendan = new Person("Brendan", 21);

Notice that the last line uses the new keyword to call into the constructor and initiate a new instance of the class with the name Brendan. This uses the constructor method from the class, which pulls in "Brendan" and 21 as its parameters to build a person named Brendan.

Say that you have a method feed as part of your class that you would like to be able to use. Here is how you use it:

Brendan.feed()

Class Inheritance

Classes are subject to inheritance, and you can pass functionality to other classes by using methods and attributes. This example shows how you can make an extension of Person called SecretAgent and give it extra properties that Person doesn’t have:

class SecretAgent extends Person {
    licenseToKill: boolean = true;
    weaponLoaded: boolean = true;
    unloadWeapon() {
        this.weaponLoaded = false;
        return "clip empty";
    }
    loadWeapon() {
        this.weaponLoaded = true;
        return "locked 'n' loaded";
    }
}

var doubleOSeven = new SecretAgent("James Bond");
let loadResult = doubleOSeven.loadWeapon();
let unloadResult = doubleOSeven.unloadWeapon();
let feedResult = doubleOSeven.feed();

So now you have a class SecretAgent that extends the Person class. This means you can still invoke the original feed method on the Person class, but it gives you some extra attributes and methods on the SecretAgent class.

Implementing Modules

Modules in TypeScript allow you to organize your code over multiple files. This helps keep your files shorter and more maintainable. Modules are able to do this by allowing you to import the functionality you need from within the module you are working on. You can do this if you export the class you need functionality from.

The following example splits the Person class into two separate modules:

module Person {
    export interface PersonInterface {
        name: string;
        hungry: boolean;
        feed();
    }
}
 
/// <reference path="Person.ts" />
module Person {
    export class Person implements PersonInterface {
    name: string;
    age: number;
    hungry: boolean = true;
    constructor(name: string, age?: number) {
        this.name = name;
        this.age = age;
    }
    feed() {
        this.hungry = false;
        return 'Yummy!';
    }
    }
}
 
var Brendan = newPerson("Brendan", 21);

In this example, the root module has the interface for Person. The submodule starts by using /// <reference path="Person.ts" /> to point to the root module so it can have access to the PersonInterface interface. The example then proceeds to build the Person class in the submodule.

Understanding Functions

Functions in TypeScript are similar to functions in JavaScript, but they have added capabilities. TypeScript functions enable you to give types to the parameters and even to what will be returned by a function. While giving a function a type is optional, it’s very helpful when you want to make sure that your functions don’t give you back something you don’t want.

TypeScript allows you to give a function a return type, much in the same way you give return types to variables. You first declare the function name and parameters, and then you can define the type of the function. Also remember that you can assign types to the parameters as well. Check out the following example:

function hello(x: string, y: string): string{
    Return x + ' ' + y;
}

Like interfaces, TypeScript functions give you the power to create optional parameters. This is helpful when you know that parameters may be circumstantial. It’s important to know that optional parameters need to come after the required ones, or an error will be thrown. The following example shows a function soldierOfGondor which takes in a required variable name, and an optional variable prefWeapon:

function soldierOfGondor(name: string, prefWeapon?: string){
    Return "Welcome " + name + " to the Gondor infantry."
}

With TypeScript functions, you can create default parameters. A default parameter is optional, but if it isn’t given, it has a default value instead of nothing. You create a default parameter by setting one of the parameters equal to the desired default value:

function soldierOfGondor(name: string, prefWeapon = "Sword"){
    return "hello " + name + " you can pick up your " + prefWeapon + " at the armory.";
}

Summary

Understanding TypeScript is critical to being able to use Angular to its full potential. This chapter goes over enough of the fundamental TypeScript properties and methods to get you through the rest of the book. You’ve learned how TypeScript uses its different types and how to write and use interfaces, classes, modules, and functions.

Next

In the next chapter you will learn about Angular and get an overview of its design and intention. Then you will learn how to create your own Angular application step-by-step, preparing you to jump into future chapters.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.149.234.188