Introduction to the environment

Czech technical University in Prague
Faculty of Information Technology
Department of Software Engineering
© Adam Vesecký, MI-APH, 2019

TypeScript

Basic types

any

void

 

boolean

number

string

Symbol

 

null

undefined

 

string[]          /* or Array<string> */

[string, number]  /* tuple */

 

false, 0, "", null, undefined, NaN  // always false

Declarations

let isDone: boolean;

const myName: string = 'Robert'// assignment

const hobbies: string[] = ['Programming''Cooking']; // array

const address: [stringnumber= ["Street"99]; // tuple

let repeatType: 'repeat-x' | 'repeat-y' | 'no-repeat'

let myCar: any = 'BMW'// any

const greeting = `Hello I'm ${userName}`// template literal

Functions

function add (a: numberb: number): number {

  return a + b

}

 

// never return type

function neverReturns(): never {

  throw new Error('An error!');

}

Enumerators

enum Color {

  Gray, // 0

  Red, // 1

  Green = 100// 100

  Blue, // 101

  Yellow = 2 // 2

}

 

const myColor: Color = Color.Green

console.log(myColor); // Prints: 100

For loop

// For..of, can be used only for iterable objects

for(let user of activeUsers) {

  console.log(user);

}

 

// for..in

// this can be applied to any object, just iterates over its attributes

// order is undefined, don't use it for iterable objects

for(let key in activeUsers) {

  console.log(activeUsers[key])

}

Crazy equality

"" == "0"          // false 

0 == ""            // true 

0 == "0"           // true 

false == "false"   // false 

false == "0"       // true 

false == undefined // false 

false == null      // false 

null == undefined  // true 

{ } === {}         // false 

new String("foo"=== "foo" // false 

10 == "10"      // true 

10 == "+10"     // true 

10 == "010"     // true 

isNan(null== false// true, null converts to 0

new Number(10)===10 // false, object and number 

Maps

// Object Map

let totalReplies = {};

totalReplies[user1] = 5// keys are converted to strings

 

// The Map -> can use strings and numbers as keys

let totalReplies = new Map();

totalReplies.set(user1, 5); 

totalReplies.set(user2, 42);

let has = totalReplies.has(user1);

totalReplies.delete(user1);

Array operations

//concat, entries, fill, filter, find, flat, flatMap, forEach, join, includes, 

//join, keys, map, push, pop, reduce, reverse, shift, slice, sort, splice, unshift, values

 

[000].fill(71// [0,7,7]

[123].find(x => x == 3// 3

[123].findIndex(x => x == 2// 1

[12345].copyWithin(30// [1, 2, 3, 1, 2]

["a""b""c"].entries() // iterator [0, "a"], [1,"b"], [2,"c"]

["a""b""c"].keys() // iterator 0, 1, 2

["a""b""c"].values() // iterator "a", "b", "c"

const merge = [...arr1, ...arr2]; // merged arrays

Other constructs

// type assertions

let len: number = (input as string).length;

let len: number = (<string> input).length;

 

// optional parameters

interface User {

  name: string// can be null but not undefined

  age?: number // can be null or undefined

}

 

// readonly

interface User {

  readonly name: string

}

 

Other constructs

// dynamic keys

{ [key: string]: Object[] }

 

// type aliases

type Name = string | string[]

 

// function types

function getUser(callback: (user: User=> any) { callback({...}) }

 

// default parameters

const greet = (name: string = 'Robert'=> console.log(`Hello, ${name}`);

 

// array destructuring

const testResults: number[] = [3.892.991.38];

const [result1, result2, result3] = testResults;

Other constructs

// arrow functions

const myMultiply: (val1: numberval2: number=> number;

 

let myFunction = (val1: numberval2: number=> {

  return val1 + val2;

}

 

// object types

let userData: { name: string, age: number } = {

  name: 'Max'

};

 

// rest operator

function displayTags(targetElement: HTMLElement...tags: string[]) { 

  for(let i in tags) { ... }  

}

displayTags(myElement, "tag1""tag2""tag3");

Classes

class Point {

 

  private x: number

  public y: number

  static instances = 0

 

  constructor(x: numbery: number) {

    Point.instances++;

    this.x = x

    this.y = y

  }

}

Inheritance

class Point {

  protected x: number;

  protected y: number;

}

 

class Point3D extends Point {

  protected z: number;

}

 

interface Colored {

  select(): void;

}

 

class Pixel extends Point implements Colored {

  select(): void { ... }

}

Getters and setters

class Plant {

  private _species: string = 'Default';

 

  get species() {

    return this._species;

  }

 

  set species(value: string) {

    this._species = value;

  }

}

Generics

class Greeter<T> {

  greeting: T

  constructor(message: T) {

    this.greeting = message

  }

}

 

let greeter = new Greeter<string>('Hello, world')

Exports and imports

export const myConst = 12345;

 

// default exports

export default calculateRectangle = (width: numberlength: number=> {

  return width * length;

}

 

// alternative

const calculateRectangle2 = (width: numberlength: number=> { ... }

export default calculateRectangle2; // exported function

export default new MyClass(); // exported instance

 

// imports

import { PI, calculateCircumference } from './src/circle'

import calculateRectangle from './src/rectangle'

import * as flash from './flash-message'// imports everything

Context binding

class ContextExample {

  private x = 0;

 

  constructor() {

    setTimeout(this.arrowFunc1000);

    setTimeout(this.regularFunc1000); // will not work

    setTimeout(this.regularFunc.bind(this), 1000);

  }

 

  private arrowFunc = () => {

    this.x = 5;

  }

  private regularFunc() {

    this.x = 5;

  }

}

Environment

Gitlab

PixiJS

  • HTML5 Creation Engine
  • Lightweight 2D JavaScript library
  • Supports both Canvas API and WebGL (since 5.x.x only WebGL)
  • Full scene graph, sprite sheets, filters, shaders,...
  • Very similar to PhaserJS game engine (yet it's way faster)
  • Performance test: link
  • Ideal for simple games and rapid prototyping

  • Main page
  • Github
  • Documentation
  • Examples

PixiJS Exercise

  • Create following animation
  • Use PIXI.Graphics