TypeScript

What is TypeScript

    Superset of JavaScript
    Strongly typed
    Supports Object Oriented design
    Angular is written in TypeScript
    Easy transition from JavaScript -- looks very similar
    Similar to strongly typed languages like C# and Java
    Can auto upgrade transpiled code as browsers support new features
    Can be used on any project type where JavaScript is used.

JavaScript vs TypeScript

Variables

variables.js
1
var foo = "Hello"; // string
2
var bar = false; // false
3
var bam = 123; // number
4
5
// can reassign type
6
foo = bar; // foo is now a boolean
Copied!

Arrays

arrays.js
1
var names = ['Bob', 'Mike', 'Jim'];
2
var ages = [10, 20, 30];
3
var friends = [{name: 'Bob', age: 10}, {name: 'Mike', age: 20}, {name: 'Jim', age: 30}];
Copied!
arrays.ts
1
var names: string[] = ['Bob', 'Mike', 'Jim'];
2
var ages: number[] = [10, 20, 30];
3
var friends: Object[] = [{name: 'Bob', age: 10}, {name: 'Mike', age: 20}, {name: 'Jim', age: 30}];
Copied!

Types in Functions

Inference

TypeScript is smart and can infer types based on what is assigned.
inference.ts
1
var foo0 = 'Bob'; // inferred as a string
2
var bar0 = 123; // inferred as a number
3
var bam0; // inferred as any
4
5
// infers the output type is a string
6
function greet1(name: string) {
7
return 'Hello ' + name;
8
}
Copied!
Specifying types makes your code more readable and will make refactors later much easier.
Avoid: Use the any type sparingly and only as a last resort. It makes your code less reliable. Consider using a pipe operator if your variable needs to support multiple types.
var foo: string | number; // accepts strings or numbers

Classes

TypeScript supports classes and can be used to create complex data structures
person-0.ts
1
class FirstPerson {
2
name: string;
3
age: number;
4
5
greet?() { // '?' signifies an optional property or method on the class
6
return 'Hi, my name is ' + this.name + ' and I am ' + this.age + ' years old';
7
}
8
}
9
10
let person0: FirstPerson = {name: 'Bob', age: 25};
11
let person1: FirstPerson = {name: 'Mike', age: 37};
12
let people0: FirstPerson[] = [person0, person1];
13
14
person0.greet(); // "Hi, my name is Bob and I am 25 years old"
Copied!

Class Constructors

person-1.ts
1
class SecondPerson {
2
name: string;
3
age: number;
4
5
constructor(name: string, age: number) {
6
// set private variables to constructor values
7
this.name = name;
8
this.age = age;
9
}
10
11
greet?() {
12
return 'Hi, my name is ' + this.name + ' and I am ' + this.age + ' years old';
13
}
14
}
15
16
let person2: SecondPerson = new SecondPerson('Bob', 25);
17
let person3: SecondPerson = new SecondPerson('Mike', 37);
18
let people1: SecondPerson[] = [person2, person3];
19
20
person2.greet(); // "Hi, my name is Bob and I am 25 years old"
Copied!

Class Constructor - Public params

Declaring parameters as public on the constructor dynamically adds a public variable to the class and no assignment is necessary.
Classes also support private and protected scoping on variables and work just like any other strongly typed language

Interfaces

TypeScript supports interfaces and enforces interface contracts. If a class implements an interface it has to implement all of the properties and methods of the interface.

ES6 Modules

TypeScript supports exporting classes, interfaces, modules, functions, and variables to be used in other files.
person-interface.ts
1
export interface IPerson {
2
name: string;
3
age: number;
4
greet?(): string;
5
}
Copied!
person.ts
1
import { IPerson } from './person-interface';
2
3
export class Person implements IPerson {
4
5
constructor(public name: string, public age: number) {}
6
7
greet() {
8
return 'Hi, my name is ' + this.name + ' and I am ' + this.age + ' years old';
9
}
10
}
Copied!
person-component.ts
1
import { Person } from './person';
2
3
let person1: Person = new Person('Bob', 25);
4
let person2: Person = new Person('Mike', 37);
5
let people: Person[] = [person1, person2];
6
7
person1.greet(); // "Hi, my name is Bob and I am 25 years old"
Copied!

Var, Let, Const?

What is the difference and when do I use which?
    Var
      Part of JavaScript and supported by TypeScript
      Are scoped to a function
      Are easily created as globals and have bad consequences
    Let
      Introduced in TypeScript
      Prefer over Var
      Block scoped
    Const
      Only assigned once
      Cannot be reassigned
      An object's properties can be reassigned

Arrow Functions

Otherwise known as fat arrow functions and sometimes called a lambda function.
    Don't have to keep typing function
    The this value of the enclosing lexical scope is used
    lexically captures meaning of arguments
    Commonly used with RxJs
1
this.configService.getConfig()
2
.subscribe((data: Config) => {
3
this.config = data;
4
});
Copied!

Template Strings

String concatenation can be messy and slow. Consider this:
template-strings.ts
1
let name = 'Bob';
2
let age = 25;
3
4
console.log('hello my name is ' + name + ' I am ' + age + ' years old');
5
6
vs
7
8
console.log(`hello my name is ${name}, and I am ${age} years old`);
Copied!
    Uses back-tick character to indicate string
    Tokens are replaced with variable values, i.e., ${variable-name}
    Can be multiline

Generics

Allows functions and classes to work with a variety of types instead of just one. This concept is borrowed from languages like C# and Java.
some-function.ts
1
// convert to allow multiple types
2
function someFunction1(arg: any): any {
3
return arg;
4
}
5
6
// convert to generic
7
function someFunction2<T>(arg: T): T {
8
return arg;
9
}
Copied!
The Angular HttpClient uses generics to enforce the type returned by our API call.
config-service.ts
1
import { Config } from './models/config';
2
3
getConfig() {
4
// now returns an Observable of Config
5
return this.http.get<Config>(this.configUrl);
6
}
Copied!

Generics with Types

Sometimes our functions need to enforce that the parameter follows a given contract.

TypeScript Transpilation

Browsers don't understand TypeScript, so it must be transpiled to JavaScript.
    tsc transpiles TypeScript to JavaScript
    tsconfig.json is used to configure tsc
    The Angular CLI handles calling tsc

Summary

    Differences between JavaScript and TypeScript
    Classes, constructors, and interfaces
    Modules
    Arrow functions
    Template Strings
    Generics
Last modified 2yr ago