TypeScript generics and animal workers

I’ve been using Java generics for years, and when I saw their syntax in TypeScript, I simply put a checkmark in the list of TypeScript features that I already know and understand.I was wrong. Let me show you something.

Below is a Java code sample that illustrates the use of generics. I’ve created a class Person and its subclass Employee. Then I created a standalone class Animal. Finally, I used the generic notation to ensure that if anyone would try to add an instance of Animal to the collection of workers, the Java compiler would complain, and it did:

Then I re-wrote the same program in TypeScript, and its compiler didn’t complain:

But if I’ll comment out the property name in the class Animal, the TypeScript compiler will complain:

This may lead to the following conclusions:

1. In TypeScript, if you use a type as a parameter in generics, it’ll allow any other type as long as it has the same properties (e.g. Person.name and Animal.name)
2. In TypeScript, animals can be workers

If there is something in TypeScript documentation that has different explanations to this behavior, please let me know. Generics is an interesting subject and I’ll write another blog soon.

TypeScript: callable interfaces

TypeScript is a superset of JavaScript and over the last year it’s gaining popularity by leaps and bounds. Angular 2 and RxJS 5 are written in Typescript. I believe about a million of developers are using TypeScript today for app development (this is not official stats). I’m using TypeScript for more than a year and it’s so much more productive than JavaScript! For me (a Java developer), TypeScript makes a lot more sense than JavaScript. But if your main language was JavaScript, some of the TypeScript’s concepts might look foreign for you. I’m planning to write a couple of blogs illustrating TypeScript syntax.

Web browsers don’t understand TypeScript and there’re no plans to change this any time soon. So if you’ll write a program in TypeScript, it has to by transpiled (think compiled) into JavaScript first. I’m not going to discuss the TypeScript compiler here, but will be using the Playground, where you can write code fragments in TypeScript, and they’ll be immediately transpiled into JavaScript (it’s going to be the ECMAScript 5 version).

TypeScript supports different flavors of interfaces. Today we’ll get familiar with a callable interface that contains a bare function signature (a signature without a function name). I’ll show you the syntax first and then will explain how a callable interfaces are useful. The following example shows a bare function signature that takes one parameter of type number and returns a boolean.

(percent: number): boolean;

The bare function signature indicates that when this function will be implemented it’s going to be callable. So what’s the big deal? Let’s consider an example that declares IPayable interface, which will contain a bare function signature. In our company work employees and contractors that will be represented by a class Person. The rules for increasing pay of employees and contractors are different, and I’ll create separate functions that implement these rules. These functions will be passed as arguments to the constructor of the class Person and will be invoked inside the constructor of the Person instances.

interface IPayable { // <1>
    (percent: number): boolean;
}

class Person  {
    constructor(private validator: IPayable) { // <2>
    }

    increasePay(percent: number): boolean { // <3>
        return this.validator(percent);
    }
}

let forEmployees: IPayable = (percent) => { // <4>
        console.log("Increasing salary by ", percent);
        return true;
    };

let forContractors: IPayable = (percent) => { // <5>
    var increaseCap: number = 20;

    if (percent < increaseCap) {
      console.log("Increasing hourly rate by", percent);
      return true;
    } else {
      console.log("Sorry, the increase cap for contractors is ",
                                         increaseCap);
      return false;
    }
}

let workers: Array<Person> = [];

workers[0] = new Person(forEmployees); // <6>
workers[1] = new Person(forContractors);

workers.forEach(worker =>worker.increasePay(30)); // <7>

1. A callable interface that include a bare function signature.

2. We declare that the constructor of the Person class takes an implementation of the callable interface IPayable as an argument.

3. The increasePay() method invokes the bare function on the passed implementation of IPayable, supplying the pay increase value for validation.

4. The rules for salary increases for employees are implemented using the arrow function expression.

5. The rules for pay increases for contractors are implemented using the arrow function expression.

6. Instantiates two Person objects, passing different rules for pay increases.

7. Invokes increasePay() on each instance, validating the 30% pay increase.

First I’ll enter the above code in the TypeScript playground on the left, and the generated JavaScript code will be shown on the right (see http://bit.ly/2hUdsGn). Read the JavaScript code – it should help you understanding what’s going on. Note, that there are no traces of our IPayable interface on the right since JavaScript doesn’t support interfaces.

play

If you click on the button Run and open the browser’s console you’ll see the following output:

Increasing salary by 30
Sorry, the increase cap for contractors is 20

Cool. But in JavaScript you can also pass a function as an argument to a higher order function (constructor in our case), right?

Now imagine that you’re supposed to pass a function with a certain signature to a higher order function, but made a mistake and passed a wrong function. This will result in a runtime error.

Callable interfaces allow you to to catch this mistake during the development stage. For that we declare the signature of a function that has to be passed to the constructor of the instance of the Person object.

Now purposely introduce an error – declare a function with the wrong signature (do it on the left side at the playground):

let forTempWorkers = () => 
      console.log("Can't increase salary for temps"); 

Try to pass it to the constructor to a Person:

workers[0] = new Person(forTempWorkers); 

TypeScript will immediately highlight the above line as erroneous, and you’ll catch this error during dev time whereas in JavaScript this error would silently sneak into your code causing the app to blow up during the runtime.

play2

So callable interfaces are your friends, aren’t they?

My Angular 2 presentations for 2017

In 2017 I’m planning to speak at several conferences related to development of Web applications with the new Angular 2 framework. Below is the list of my presentations (each one is 90-min long). All of them can be delivered as a 2-day workshop in your organization.

Mastering TypeScript

TypeScript is a superset of JavaScript, which allows you to be more productive in writing JavaScript applications. The syntax of this language is pretty easy to pick up for anyone who’s familiar with such object-oriented languages as Java or C#. During this presentation you’ll learn the syntax of this language and will understand the benefits it brings to the table.

Make a facelift to your Angular 2 app with UI libraries

Commercial applications need to be good looking, which means that you should pick up a rich library of UI components for your app. While Angular Material library offers two dozen of great looking components, this may not be enough for your application needs. The good news is that there are other libraries that you can use. In this presentation we’ll start with an overview of Angular Material components. Then we’ll proceed with another open-source library called PrimeNG, which offers more than 70 UI components. Finally, we’ll review the code of an Angular 2 app that uses both Angular Material and PrimeNG components.

Angular 2 for Java developers

Angular 2 is a complete re-write of the super popular Web framework AngularJS. According to Pluralsight survey, Angular leads the list of what developers want to learn in 2016. Angular 2 is a component-based framework that will have an effect in JavaScript community similar to what Spring framework did for Java. This presentation is an overview of this hot framework, which in combination with TypeScript, finally made Web development understandable for Java developers. At the end of the presentation you’ll see a sample Web application written in Angular 2 on the front and Java on the server.

Angular 2: Working with the component router

In this session you’ll see how to use the router that comes with Angular 2 Final. We’ll start with configuring the navigation in a simple app. Then you’ll see how to pass data to routes, work child routes, and create apps with multiple router outlets (auxiliary routes). We’ll also review a unit-test configuration for testing router. Finally, you’ll see how how to lazy load modules using the router.

Angular 2: Communication with the server via HTTP and WebSocket protocols

In this session you’ll see how create an Angular 2 app that can communicate with the servers via a pull (HTTP) and push (WebSocket) modes. We’ll program a simple Node server and then will go through a number of code samples that communicate with it using HTTP and WebSocket protocols. We’ll start with creating a simple NodeJS server, and then will enable it to handle HTTP requests from an Angular 2 app. Then you’ll see how to wrap a service into an observable stream. Finally, we’ll teach our server to perform a data push to an Angular 2 client using the WebSocket protocol.

Implementing inter-component communication in Angular 2

Angular 2 is a component-based framework with a well-defined API for passing data to and getting data from a component. Any application is a tree of components that often need to communicate with each other.
In this presentation you’ll see how to create reusable application components that can exchange data with each other in a loosely-coupled manner. You’ll see how components can communicate via a common parent or via an injectable service. You’ll see how to pass data using component router, input and output parameters, events and callbacks. You’ll also learn how to use projection (formerly known as transclusion) to pass HTML fragments to a component’s template. We’ll also touch upon the incorporation of the third-party JavaScript libraries into an Angular 2 app.

Using Observable Streams in Angular 2

Angular 2 includes RxJS, which is a library of reactive extensions built on the premise that everything is an observable stream.

Observables allow to introduce the push model to your application. First we’ll get familiar with the RxJS library, and then will continue reviewing observables in Angular 2. In this presentation you’ll see how to treat UI events, HTTP, and WebSocket connections as observable streams that push data. You’ll see how to wrap up any service into an observable stream so your application components can subscribe to it.

Angular 2 Tooling

Learning Angular 2 is easier than AngularJS, and developing in TypeScript is more productive than in JavaScript. But setting up the project and deploying the application is not straightforward. This presentation is not about the Angular 2 syntax. We’ll discuss the development process with Angular 2 starting from setting up the project to deploying an optimized application. We’ll start with discussing the Angular/TypeScript project structure and the proceed with such topics as using the module loader SystemJS, installing type definition files, bundling the app with Webpack and deployment in dev and prod. Finally, we’ll go through the process of scaffolding and bundling projects using the Angular CLI tool.

Angular 2: Component communication with events vs callbacks

So a child component needs to pass some data to its parent. I use TypeScript and in this blog I’ll show you two techniques: events vs callbacks.

Emitting events

The technique with emitting events is well documented:

1. Declare a property of type EventEmitter and instantiate it
2. Mark it with an @Output annotation
3. Be nice. I mean use generics to make it obvious to other developer what are you emitting and let TypeScript compiler warn you it you’ll try me emit the object of the wrong type.

The next line shows you an example that implements all three steps in a component called PriceQuoterComponent, which will be emitting price quotes of type IPriceQuote.

@Output() lastPrice: EventEmitter <IPriceQuote> = 
                              new EventEmitter();

The above code is very declarative and easy to read even after I quit and will go to work for another company.

To actually emit/dispatch/fire the lastPrice event, you need to create an object of type IPriceQuote and invoke the function emit:

let priceQuote: IPriceQuote = {...};
this.lastPrice.emit(priceQuote);

Nice an clean. Our component is loosely coupled and reusable, because it has no strings attached to any other components. It just shoots the lastPrice event with a payload to whoever cares to listen (or subscribe) to this event. For example, a parent component can do it like this:

<price-quoter (lastPrice)="priceQuoteHandler($event)">
</price-quoter>

The event handler function is also very easy to understand, especially because its argument explicitly declares the type of the object its getting:

priceQuoteHandler(event:IPriceQuote) {...}

Callbacks

Not sure why do you even want to go this route. Most likely, because you’ve never been in the callback hell. Get ready to lose the goodness of explicit typing and be prepared to deal with the “this and that” problem. But if you insist, I’ll show you how to do it.

This time the child (PriceQuoterComponent) will declare an @Input property, which will accept the name of the callback function to be called on the parent. Remember the Hollywood principle “Don’t call me, I’ll call you”?

@Input() whoToCall: Function;

The parent will bind the name of its function to call. Now, the child instead of emitting the event will call that function on its parent:

let priceQuote: IPriceQuote = {...};

this.whoToCall(priceQuote);

The parent won’t be listening to child’s events because there won’t be any. But now the parent needs to do two things:

1. Declare and bind the function that has to be called by the child

2. Ensure that it’ll be invoked in the object that represents the parent and not on a global object. We need to pass the “this” object to the bound function, which can be done using arrow functions in ES6 or the function bind() in ES5:

@Component({
...
    template: `
   <price-quoter [whoToCall] ="fnPriceQuoteHandler">
   </price-quoter>`
})
class AppComponent {

    fnPriceQuoteHandler: Function;

    ngOnInit(){
        this.fnPriceQuoteHandler= 
              obj => this.priceQuoteHandler(obj); // ES6

        // this.fnPriceQuoteHandler=
        //     this.priceQuoteHandler.bind(this); // ES5
    }
}    

In this video I did a quick code overview of both implementations of the above components. The sources are here. I like the version with events better, and you?

Adding PrimeNG UI components to Angular CLI projects

Angular 2 CLI is a scaffolding tool and code generator that can be used for the real world projects. It saves you a lot of typing and spares you from worrying about config files for TypeScript compiler, testing frameworks, project bundler (it uses Webpack), and deployment.

PrimeNG is an excellent library of 70+ Angular 2 UI components. In this blog I’ll list the steps you need to perform to generate new project with Angular CLI and add PrimeNG library to this project.

If you don’t have Angular CLI installed yet, install it globally:

npm install @angular/cli -g

In the terminal window generate a new project, e.g. primeng_with_cli. Since I just want Angular CLI to generate only app compnent and module files, I’ll specify the option to generate inline template and styles and don’t bother with the test spec:


ng new primeng_with_cli --it --is --spec=false

Change to the newly created directory

 
cd primeng_with_cli

Add font awesome and PrimeNG as dependencies in package.json, e.g.


"font-awesome": "^4.6.3",

"primeng": "^1.0.0-beta.20",

Since the package.json was modified, install the above dependencies:

npm install

PrimeNG requires certain global styles so its components look pretty. Angular CLI projects have a config file angular-cli.json, where you can configure project settings, and in particular it has the property styles, which is the right place to add global style. Yes, I’m talking about the style tages that you’d add in the index.html in a regular Web app.

Angular CLI generate an empty file style.css and you need to add three more CSS file that are needed for PrimeNG:


"styles": [
    
  "styles.css",

  "../node_modules/primeng/resources/themes/omega/theme.css",

  "../node_modules/font-awesome/css/font-awesome.min.css",

  "../node_modules/primeng/resources/primeng.min.css"

] 

For sanity check run your new app by entering the following command in the terminal window:

ng serve

Open the app in the browser at 
http://localhost:4200, and Webpack dev server will happily render the single-page app with the text app works! This is a basic app that Angular CLI generated for you.

Now you need to modify the code in the generated dir app.component with the code that uses PrimeNG components. You can take the sample code from this blog. You’ll need to add required PrimeNG components to imports and declarations in the application module file app.module.ts.

The dev version of the app works, and now let’s see the prod version of this cool app. To prepare a production build run this command:

ng build --prod

Angular CLI will create bundles and will deploy all the files in the dist directory of your project. Take a peek into this directory and you’ll see the bundles that are available as .js files as well as their gzipped versions. The question is, how can we serve the existing gzipped files without having the web server do it for us? A simple solution is to install a static Node server that knows how to do it. Just add node-static package as dev dependency in package.json and install it:


"node-static": "^0.7.9" 
npm install

Finally, add the following npm script command in scripts section in package.json:



"serve:dist": "static dist -H '{\"Cache-Control\": \"no-cache, must-revalidate\"}' -z"

Start the static server and it’ll serve the optimized app on port 8080:



npm run serve:dist

NOTE: Creators of PrimeNG promised to add AoT support in the release candidate that will be available within a couple of weeks. When it’s done, you’ll be able to create smaller bundles by running this command:

ng build --prod --aot

That’s all folks!

Angular 2 training for your organization

If your team is interested in a hands-on, in-depth exploration of how to develop web applications with Angular 2, I can run a three day workshop in your organization. Participants will gain practical, skills while exploring the best practices and principles of developing Angular 2 applications and get familiar with multiple sample applications illustrating solutions for real-world challenges.

By the end of this live, hands-on course, participants will understand:

  • How to jump-start a new Angular project
  • How to arrange the client-side navigation in single-page applications
  • How to communicate with servers using HTTP and WebSocket protocols

And they’ll be able to:

  • Write code in TypeScript with the Angular 2 framework and deploy it in any modern web browser
  • Unit test the router, services, and components
  • Automate the building and deployment processes using the Webpack bundler and npm scripts

About your instructor

Yakov Fain is the coauthor of Angular 2 Development with TypeScript as well as a number of other technical books on programming. Yakov works as a software architect at the IT consultancy Farata Systems and develops software products for the insurance industry. A Java Champion, he has taught multiple classes and workshops on web and Java-related technologies, presented at international conferences, and published more than a thousand blog posts. Yakov lives in New York City.

What former clients say about Yakov’s Angular 2 workshops:

“The workshop is exactly what I have envisioned. The contents cover all of the critical and important aspects of the platform. It is also very hands-on. You made the training fun and engaging. The pace is also just right for impatient developers like us.”
– Emily Jeng, Princeton University

“I’ve attended several of your courses already. I think the plan and coverage are really comprehensive. I liked how we were going from a starter to the complete solution during the course and didn’t forget to talk about pros and cons and alternatives (several ways to build a form, SystemJS versus Webpack, etc.).”
— Dmitry N.

“Great class. Very thorough and great, detailed examples.”

— Coral S.

Prerequisites

Attendees must have basic knowledge of JavaScript and HTML. If you never worked with JavaScript before, please watch this video from one of the previous Yakov’s trainings. No knowledge of AngularJS 1.x is required.

Course outline

  • Unit 1. First steps with Angular 2
    • Introduction to Angular 2 architecture
    • Project structure and setup with npm
    • Brief introduction to TypeScript
    • Creating a “Hello World” app
    • Using the SystemJS loader
    • Templates and bindings
    • An overview of a sample Online Auction app
  • Unit 2. Client-side navigation and inter-component communications
    • Intro to client-side navigation with component router
    • Child routes, multiple router outlets, lazy loading of modules
    • How to install and use type definition files
    • Intercomponent communications
    • Implementing the mediator pattern
    • Projection of HTML fragments
  • Unit 3. Dependency injection and observable streams
    • Dependency injection
    • Providers and injectors
    • Promises (pull) versus Observables (push)
    • Observable events
    • Observable HTTP requests
    • Code review of the Online Auction
  • Unit 4. Working with Forms API and component life-cycle
    • Basic forms with ngModel
    • Template-driven forms
    • Model-driven forms
    • Form validation
    • The component life-cycle and hooks
    • How change detection works
  • Unit 5. Communicating with a server via the HTTP and WebSocket protocols
    • Creating a simple HTTP server with the Node.js and Express frameworks
    • Working with HTTP objects
    • Benefits of the WebSocket protocol over HTTP
    • Working with WebSockets
  • Unit 6. Unit testing and build automation
    • Unit testing with Jasmine
    • How to unit test Angular services, router, and components
    • Running tests with Karma
    • Getting familiar with the Webpack bundler
    • Working with Angular CLI

During this code participants performs many hands-on exercises. After each unit participants will spend half an hour working on a sample Online Auction app.

How to arrange this on-site training in your organization

This training is offered by Farata Systems, an IT consulting and training company. For training inquiries send an email at training @ faratasystems.com