Editors/Installation

  • sudo npm -g install TypeScript
  • inteij include File plugin that will add a default watcher for Typescript

Language

Options Types Definitions

Typescript allows you to add optional types with a “:type” keyword additions These include

  • string
  • number
  • boolean
  • string[]
// primitive type annotation
var name: string = 'Steve';
var heightInCentimeters: number = 182.88;
var isActive: boolean = true;
 
// array type annotation
var names: string[] = ['James', 'Nick', 'Rebecca', 'Lily'];
 
// function annotation with parameter type annotation and return type annotation
var sayHello: (name: string) => string;
 
// implementation of sayHello function
sayHello = function (name: string) {
return 'Hello ' + name;
};
 
// object type annotation
var person: { name: string; heightInCentimeters: number; };
 
// Implementation of a person object
person = {
name: 'Mark',
heightInCentimeters: 183
}; 

Ennumeration

enum VehicleType {
   PedalCycle,
   MotorCycle,
   Car,
   Van,
   Bus,
   Lorry
}
 
var type = VehicleType.Lorry;

Methods

Classes

Constructors

  • All classes in TypeScript have a constructor, whether you specify one or not. One is automatically generated if not specified.
class Song {
   constructor(private artist: string, private title: string) {
 
   }
}

Exception Handling

try {
   var result = errorsOnThree(3);
} catch (err) {
   console.log('Error caught, no action taken');
}

Async

https://blog.mariusschulz.com/2016/12/09/typescript-2-1-async-await-for-es3-es5

function delay(ms) {
    return new Promise(function (resolve) {
        setTimeout(resolve, ms);
    });
}
async function asyncAwait() {
    console.log("Knock, knock!");
    await delay(1000);
    console.log("Who's there?");
    await delay(1000);
    console.log("async/await!");
}

Simple Express Server

import express = require('express');
import http = require('http');
 
var app = express();
app.set('port', process.env.PORT || 3000);
app.get('/', function(req: express.Request, res: express.Response) {
  res.send('Hello world!');
});
 
http.createServer(app).listen(app.get('port'), function() {
  console.log('Express server listening on port ' + app.get('port'));
});
 
typescript.txt · Last modified: 2018/06/28 01:37 by root
 
RSS - 200 © CrosswireDigitialMedia Ltd