• Stars
    star
    184
  • Rank 209,253 (Top 5 %)
  • Language
    TypeScript
  • Created about 12 years ago
  • Updated over 9 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

AngularJS + Typescript presentation and example

AngularJS + Typescript ♥♥

Follow Along:

github.com/seanhess/angularjs-typescript

video from ng-conf 2014

About Me

Sean Hess

Code and Startups

WHY TYPESCRIPT?

Story of a Javascript App

  • started fast with JS
  • house of cards
  • testing was hard

Typescript: be happy

  • like waking up on Christmas with well-written, fast tests
  • formalize your choices as you go
  • modern features make it easy: optional, inferred

see mistakes right away, in context

Editor Errors

autocomplete

Editor Autocomplete

WHAT IS TYPESCRIPT?

  • basically compiles ES6 to JavaScript
  • plus a modern type system

Getting Started

Install Typescript

> npm install -g typescript

It is just JavaScript/ES6

function hello(name) {
    alert("hello " + name)
}
hello("world")

Compile It

> tsc test.ts

Add Types to Variables

Try these in the Typescript Playground: www.typescriptlang.org/Playground

var population:number = 3

var name:string = "hello"
var names:string[] = [name];

var user:User;

var couldBeAnything;

Produces output that looks the same

Interfaces

Make some rules and keep them

interface User {
    firstName: string;
    lastName: string;
}

// interface matches any object with the right fields
var user:User = {firstName:"Very", lastName:"User"}
var user2:User = {name:"Very User"} // error

function fullName(user:User):string {
    return user.firstName + " " + user.lastName;
}

Type Inference

The compiler can read your mind

Telepathy

// name is a string
var name = fullName(user)

function sum(a:number, b:number) {
    return a + b
}

var result = sum(name, 4)

Generics

Code for what things have in common

function firstValue<T>(array:T[]):T {
    return array[0]
}

// these will give errors.
var one:string = firstValue([1,2,3,4,5])
var two:number = firstValue(["one", "two"])

ES6 Features

External Modules: can output CommonJS or AMD

// users.ts
export function fullName(user:User):string {
    return user.firstName + " " + user.lastName
}

// main.ts
import users = require("./users")
var name = users.fullName(user)

Internal Modules

module users {
    export function fullName(user:User):string {
        return user.firstName + " " + user.lastName
    }
}

var name = users.fullName(user)

Classes

class Animal {
    public size:number;
    constructor() {
        this.size = 0;
    }
}

class Kitten extends Animal {
    public furriness:number

    devour(animal:Animal) {
        this.size += animal.size
    }

    get isCute() {
        return (this.size < 10 && this.furriness > 5)
    }
}

Fat Arrow Functions

var service = {
    names: [],

    loadNames: function() {
        $.get("/users", (users) => {

            // cheap inline functions
            var firstNames = users.map((user) => user.firstName)

            // "this" still works!
            this.names = firstNames
        })
    }
}

Definition Files

External type definition files for many libraries on DefinitelyTyped

declare module ng {
    interface IScope {
        $parent:IScope;
        $eval(expressions:string):any;
        $watch(expressions:string):any;
        ... 
    }
}

function MyController(scope:ng.IScope) {}

IDE and Editor Integration

Error checking and Autocomplete:

TYPESCRIPT + ANGULAR

Add Typescript to TodoMVC AngularJS

Start with TodoMVC, let's add Typescript to it

http://todomvc.com/architecture-examples/angularjs/

Start with your Data Model

Make a file with shared application types: types.ts. Data first design.

interface Todo {
    completed: boolean;
    title: string;
}

Add :Todo to function signatures

function createTodo(text):Todo {
    return {
        title: text,
        completed: false
    }
}

Add Definition Files

/// <reference path="./types/jquery/jquery.d.ts"/>
/// <reference path="./types/angularjs/angular.d.ts"/>
/// <reference path="./types/angularjs/angular-route.d.ts"/>

interface Todo {
    completed: boolean;
    title: string;
}

Angular Controller

Start with todoCtrl.js

todomvc.controller('TodoCtrl', function TodoCtrl($scope, $routeParams, todoStorage, filterFilter) {
    var todos = $scope.todos = todoStorage.get();
    ...
})

todoCtrl.ts: Add some interfaces for the scope and params

interface TodoCtrlScope extends ng.IScope {
    todos:Todo[];
    newTodo:string;
    editedTodo:Todo;
    originalTodo:Todo;
    remainingCount:number;
    completedCount:number;
    allChecked:boolean;
    status:string;
    statusFilter:{completed:boolean};

    addTodo();
    editTodo(todo:Todo);
    doneEditing(todo:Todo);
    revertEditing(todo:Todo);
    removeTodo(todo:Todo);
    clearCompletedTodos(todo);
    markAll(completed:boolean);
}

interface TodoCtrlRouteParams {
    status:string;
}

Add types to the parameters

todomvc.controller('TodoCtrl', function TodoCtrl($scope:TodoCtrlScope, $routeParams:TodoCtrlRouteParams, todoStorage:TodoStorage, filterFilter) {
    var todos = $scope.todos = todoStorage.get();
    ...
})

To use classes consider the view model method

Angular Service

Start with todoStorage.js

todomvc.factory('todoStorage', function () {
    var STORAGE_ID = 'todos-angularjs';

    return {
        get: function () {
            return JSON.parse(localStorage.getItem(STORAGE_ID) || '[]');
        },

        put: function (todos) {
            localStorage.setItem(STORAGE_ID, JSON.stringify(todos));
        }
    };
});

To make todoStorage.ts, let's use a class

class TodoStorage {
    static STORAGE_ID = 'todos-angularjs';

    // dependencies would be injected here
    constructor() {

    }

    get():Todo[] {
        return JSON.parse(localStorage.getItem(TodoStorage.STORAGE_ID) || '[]');
    }

    put(todos:Todo[]) {
        localStorage.setItem(TodoStorage.STORAGE_ID, JSON.stringify(todos));
    }
}

for classes use .service() instead of .factory()

todomvc.service('todoStorage', TodoStorage)

Lets you formalize an API

Alternatively, you could just add an interface

Add a build step

Add a build step to your Gruntfile.js

grunt.initConfig({
    exec: {
        tsPublic: { cmd: 'node_modules/.bin/tsc public/js/app.ts public/js/**/*.ts -t ES5'},
    },

    watch: {
        public: {
            files: ["public/**/*.ts"],
            tasks: ["exec:tsPublic"],
            options: { livereload: true },
        },
    }
})

grunt.registerTask('default', ['exec:tsPublic', 'watch'])

Then just run grunt, and start saving files

> grunt

No way to type views :(

<!-- should be .title, but no error -->
<label>{{todo.text}}</label>

Using ES6 Modules

  • simplest: just include all the generated .js files
  • add a build script: grunt concat
  • namespaces? use internal modules
  • with browserify or AMD: use external modules

Live Code: Refactoring a Service

  • Let's add promises! What could go wrong?
  • Typescript will save us!

What about Dart? Coffeescript?

  • There can be only one
  • was worth giving up Coffeescript
  • Dart has a cool type system, but it is all-in.

Other cool things you could try:

  • Rich models with classes

IT'S OVER!

github.com/seanhess/angularjs-typescript

Concat Me: @seanhess

TODO: paste in images of IDEs

More Repositories

1

wizardwar

Wizard War is an open-source multiplayer iOS game
Objective-C
550
star
2

functional-javascript

Functional Javascript: The Good Parts
98
star
3

hyperbole

Haskell interactive serverside web framework inspired by HTMX
Haskell
79
star
4

runtime-types

Use flow type information at runtime. Useful for validations, mapping to an ORM, and more.
JavaScript
70
star
5

robotquest

RobotQuest is a MMO, programming game. Instead of playing RobotQuest directly, you write a program that plays it for you. Your program communicates with the game server API over HTTP by sending and receiving JSON messages. Written in HTML, Haskell, with MongoDB
Haskell
59
star
6

ios-firebase-objects

High level collections and other objects to make Firebase easier
Objective-C
46
star
7

web-view

Typed HTML with simplified layout, and easy composable styles. Inspired by Tailwindcss and Elm UI
Haskell
34
star
8

html5-drag-drop-anything

Slides and Code for "HTML5 Drag and Drop Anything" Presentation
CoffeeScript
28
star
9

practical-haskell

Source code for series of Haskell tutorials
Haskell
24
star
10

Blog

custom ruby blogging system
Ruby
23
star
11

serials

"Podcasts app" for serial webfiction and webcomics.
JavaScript
19
star
12

wolfpack-ios

Wolf Pack
Objective-C
15
star
13

the-issues-angularjs-demo

"Versus" demo application written in AngularJS
JavaScript
12
star
14

tpm

Typescript client-side dependencies made easy
TypeScript
11
star
15

bifff

Behavior Injection for Flex - a jQuery-like behavior injection framework for flex
ActionScript
10
star
16

node-ftpclient

FTP client for node.js
JavaScript
10
star
17

dont-fly-alaska-air

@DontFlyAlaska is a good-natured revenge twitter account powered by a Haskell robot
Haskell
9
star
18

centos

Centos Shell Script Functions
Shell
8
star
19

yeti

Haskell
8
star
20

cocomo-tutorial

A string of tutorial examples on Adobe Cocomo - building up to a shared model
ActionScript
7
star
21

seanhess.github.com

seanhess.github.com
HTML
7
star
22

glue

Beautiful Gooey MVC Framework for Flex
JavaScript
7
star
23

flexorm

A fork of FlexORM on google code
ActionScript
6
star
24

ratinatorly

Who rates the rate-men?
JavaScript
6
star
25

librosapp

Libros - Spanish iOS audio and text bookstore and reader
Objective-C
6
star
26

bombs

A multiplayer game written in flex with AFCS
ActionScript
5
star
27

serverless-haskell-miso

Serverless haskell web application
Haskell
5
star
28

php-light-socket-server

A Socket server written in PHP
4
star
29

rich-text-area

A refactor of Flex's Rich Text Editor
ActionScript
4
star
30

mts

MiniTiddlyServer - a php backend for TiddlyWiki (not supported!)
PHP
4
star
31

atom-typescript

Typescript Language Support for Atom Text Editor with IDE-like features.
CoffeeScript
3
star
32

flashlib

An index of sweet flash, flex and as3 code
Ruby
3
star
33

shared-model-server

An implementation of PHP Light Socket Server for Shared Models in Flex
PHP
3
star
34

flay

A Library of Super-Flexible Flex Containers and Lists
ActionScript
3
star
35

degrafa-path-demo

An interactive demo that lets you type in degrafa code and show stuff
JavaScript
3
star
36

deathbycute

A example game with a shared model using Adobe Cocomo
ActionScript
3
star
37

wai-middleware-headers

addHeaders and cors for Haskell's Network.Wai
Haskell
3
star
38

blockworld

Objective-C
3
star
39

afcs-uvu

Some demos for a lecture at the local university
2
star
40

haskell-tdd-kata-roman-numerals

TDD in Haskell with a Roman Numerals kata
Haskell
2
star
41

CATiledLayer-Example

CATiledLayer Example
Objective-C
2
star
42

bombs-deploy

The deploy files for bombs
JavaScript
2
star
43

mate-presentation-model

Contains an example of using a presentation model in mate
2
star
44

VIntage

Objective-C
2
star
45

zombie-example

restful x example with zombies
ActionScript
2
star
46

node-mail

Fork of mail from npm
JavaScript
2
star
47

elm-introduction

Introduction to Elm
Elm
2
star
48

learn-flex

Some assignments to learn flex
JavaScript
2
star
49

lightsockflex

Flex client for Light Socket
2
star
50

flight-and-mate-example

A side-by-side bookstore example of flight and mate
2
star
51

Data-Driven-Views-Presentation

Objective-C
1
star
52

cprt

Base management app for our alien defense roleplaying game.
JavaScript
1
star
53

LDS-Activity-Demo

Objective-C
1
star
54

physics

JavaScript
1
star
55

mebipenny

JavaScript
1
star
56

simple-deploy-example

Example of Simple Custom Deployment
1
star
57

corpse

Exquisite Corpse for groups with a billion phones
1
star
58

helium

dynamic javascript iOS framework
1
star
59

uarbg

JavaScript
1
star
60

icarus

Interactive fiction in space!
JavaScript
1
star
61

node-async-framework-temp

Temporary Home for Node Async Framework
JavaScript
1
star
62

elm-components

Elm Components
Elm
1
star
63

node-router

CoffeeScript
1
star
64

cards2

JavaScript
1
star
65

MarketHealth

JavaScript
1
star
66

gendocs

Haskell
1
star
67

amqp-worker

Type-safe AMQP workers
Haskell
1
star
68

advent-of-code-2018

Haskell
1
star
69

blocks-presentation

Objective-C
1
star
70

flog

Flex Logging Sugar
ActionScript
1
star
71

happstack-ella

Small Sinatra-like wrapper for happstack-lite
Haskell
1
star
72

sublime-build-errors

See errors from Grunt or other command-line programs
Python
1
star
73

dotfiles

Lua
1
star
74

Flex-Framework-Deathmatch

An editable dictionary client implemented in multiple frameworks
PHP
1
star
75

spoticka

Spotika
JavaScript
1
star
76

picture-directory

picture directory
Haskell
1
star
77

AFCS-Examples

Examples for Flex 360 Presentation
JavaScript
1
star
78

Helium2

Objective-C
1
star
79

uarbg2

Underwater Adventure Rocket Bazooka Guys v2
JavaScript
1
star
80

mongol

CoffeeScript
1
star
81

elm-sandbox

Playing with elm
JavaScript
1
star
82

zero

Alternative Flex DI Framework
ActionScript
1
star
83

mongodb-sites-example

1
star
84

haskell-docker-example

Bug with stack image container
Haskell
1
star