Get Hyped For Types
An Introduction to TypeScript
About Me
Warren Seymour
Owner, Fountainhead Technologies Ltd.
Using TypeScript for ~4 years
warren@fountainhead.tech
Untyped
- Data is just a collection of bits
- Any operation is permitted on any piece of data
- Errors will manifest themselves at run-time
Typed
- Data has a value and a type
- Operations may only apply to specific types or combinations
- Validity is checked at compile-time
var a = 10;
var b = 20;
var c = "hello";
var d = " world";
a + b; // 30
c + d; // "hello world"
a + c; // "10hello"
int a = 10;
int b = 20;
str c = "hello";
str d = " world";
a + b; // 30
c + d; // "hello world"
a + c; // Compiler error
Static
Type-checking occurs at compile-time
Dynamic
Type-checking occurs during run-time
Weak
One type may be treated as another
Strong
Types may only be treated according to their declaration
Assembly - Untyped
JavaScript, PHP - Weak, Dynamic
Java, C - Strong, Static
Enter TypeScript
What is TypeScript?
- Introduced in October 2012
- A static, strongly typed superset of JavaScript
- Transpiles to JavaScript for execution in the browser or Node
(or Electron/React Native/etc)
Why use TypeScript?
- More reliable programs
- Avoid silly mistakes
- Reduced exposure to JavaScript's 'bad parts'
- Huge productivity gains
- Better designed programs
- Code intelligence
- Pleasurable (?) refactoring
- Less tests
- ES6 constructs & syntax supported
Who makes TypeScript?
- Free and Open Source
- Developed and maintained by Microsoft
- Lead by Anders Hejlsberg
- Wrote Turbo Pascal
- Lead on Delphi and C#
-
Mature, stable
- Currently at version 2.8
- New features coming bi-monthly
The Basics
// Plain JavaScript, get type checking for free
var now = new Date();
console.log(now + 10);
// Parameter 'name' has an implicit 'any' type
function greet(name) {
console.log('Hello, ' + name);
}
greet('Warren');
// Make 'name' parameter type 'string'
function greet(name: string) {
console.log('Hello, ' + name);
}
greet('Warren');
greet(123);
// Declare variable 'x' a 'number'
var x: number = 12;
x = 'Hello';
// Working with arrays
function sum(xs: number[]) {
return xs.reduce(function(total, x) {
return total + x;
}, 0);
}
console.log(
sum([4, 8, 15, 16, 23, 42])
);
// Function return type 'void'
function greet(name: string): void {
console.log('Hello, ' + name);
}
// Function return type 'string'
function greet(name: string): string {
return 'Hello, ' + name;
}
function greet(name: string): void {
return 'Hello, ' + name;
}
function greet(name: string): string {
console.log('Hello, ' + name);
}
TypeScript Constructs
// Defining an 'interface'
interface Person {
name: string;
age: number;
pets: string[];
}
// Using as a function parameter type
function greetPerson(person: Person) {
console.log('Hello, ' + person.name);
}
greetPerson('warren'); // Nope
greetPerson({
name: 'Warren',
age: 32,
pets: ['Jerry']
});
// Enumeration types
enum Direction {
North,
East,
South,
West
}
function move(dir: Direction) {
if (dir === Direction.North) {
console.log('you were eaten by a grue');
}
}
move(Direction.North);
move('north');
// See also - 'const enum'
// Union types
function double(x: string | number) {
if (typeof x === 'string') {
return x + ' ' + x;
}
if (typeof x === 'number') {
return x * 2;
}
}
double(8);
double('hello');
double(true);
// Intersection types
interface Person {
name: string;
}
interface PetOwner {
pets: string[];
}
function showNameAndPets(person: Person & PetOwner) {
console.log('Name:', person.name);
console.log('Pets:', person.pets.join(','));
}
Generics
- A 'container' of another type
-
string[] -> Array<String>
-
Promise<Person>
-
- Type Parameters - 'placeholders' in function declarations, interfaces and aliases
interface Person {
name: string;
}
function fetchUser(id: number): Promise<Person> {
return fetch('/users/' + id);
}
fetchUser(1337)
.then(function(person) {
console.log(person.name);
});
interface Person {
name: string;
}
function fetchUsers(name: string): Promise<Array<Person>> {
return fetch('/users?name=' + name);
}
fetchUsers('warren')
.then(function(people) {
var names = people
.map(person => person.name)
.join(',');
console.log(names);
});
// Declare 'T' as a 'Type Parameter'
function identity<T>(x: T): T {
return x;
}
// Get first array element, retaining type information
function head<T>(xs: T[]): T {
return xs[0];
}
Using TypeScript Today
-
npm install typescript --save-dev
-
tsc --init
-
npm install @types/* --save-dev
Get Hyped For Types
By Warren Seymour
Get Hyped For Types
- 834