TypeScript
TypeScript lets you write JavaScript the way you really want to.
TypeScript is a typed superset of JavaScript that compiles to plain JavaScript. Any browser. Any host. Any OS. Open Source.
What is it?
- Introduced in October 2012 by Ander’s Hejlsberg
- Free & Open source language
- It is a “superset of JavaScript”
- Build Plugins for maven, gradle, grunt and gulp
- Rapidly becoming an Industry Standard (Angular)
What is a superset?
It's ES2015!
- Arrow Functions
- Spread
- Block scoping (let & const)
- Classes with constructors, get/set
- Enhanced Object Literals
- Template Strings
- Destructuring
- Iterables and Iterators
- Types
- Decorators (from ES7)
- Generics
- Enums!
- Class Extensions
- Access Modifiers
- Interfaces
- Access Modifiers
- Namespaces
Plus
Why use TypeScript?
- It's JavaScript, but better...with intellisense and API help
- Built for JavaScript at Scale
- Smaller Transpiled output than ES2015's
- Help's Identify Bugs during design... instead of after deployment
- Easy to configure
- Better overall code readability in large codebases
- Ease of refactoring
- Use new ES6 features in older browsers
- IntelliSense auto suggest in code editors
Design Time Analysis
- Finding bugs earlier in your development process
- Fix a bug in your logic at design time rather than fixing the bug at run time.
- A compile-time bug will fail every time you run the compiler, but a runtime bug can hide until the exact scenario that triggers it is manually stumbled upon.
- Runtime bugs can slip under a crack in your logic and lurk there (sometimes for months) until discovered.
TS is JavaScript at Scale
- Checks code on the fly at design time
- Compatible with most editors, via plugins to:
- Provides custom code completion
- Error identification via tooltips (with plugin support)
- Allows you to catch bugs prior to JS build
- Compatible with most editors, via plugins to:
- Transpiles to ES5
- Plugs right in where babel is used to transpile ES2015
- tsc watcher for compiling on save
- You can see the ES5 output live (split-plane)
- ES5 output is ~HALF the size of Babel’s
TypeScript Transpilation
- Why is it smaller?
- No type checking required in our code
- No type checking added into the output
// ES2015
doSomething (smidge) {
if (smidge instanceOf repo
&& smidge.myProp) {
let a = smidge.myProp;
}
//...
}
// Transpiled ES5
function doSomething (smidge) {
if (smidge instanceOf repo
&& smidge.myProp) {
var a = smidge.myProp;
}
//...
}
// TypeScript
doSomething (smidge:repo) {
let a = smidge.myProp;
...
}
// Transpiled ES5
function doSomething (smidge) {
var a = smidge.myProp;
...
}
Easy to configure
tsconfig.json:
{
"compilerOptions": {
"module": "commonjs",
"noImplicitAny": true, // to allow untyped vars
"removeComments": true,
"preserveConstEnums": true,
"out": "/build/app.js",
"sourceMap": true
}
}
TypeScript Features
- Types + Void + Any
- Optional Parameters
- Decorators
- Generics
- Enums
- ...
TypeScript Types
var num: number = 123;
function identity(num: number): number {
return num;
}
identity('string'); // error!
var myNumbers : number[] = [170, 2.6, 2245, 3032, 400];
Void & Any
function initSomething() : void {
doSomeStuff();
}
var pointless = initSomething(); // Compiler Error
// if you absolutely have to (don't do it young Jedi!)
var foo : any;
foo = 'Hello!';
foo = true;
foo = 42;
Optional Parameters
buildName(firstName: string, lastName?: string {
if (lastName) {
return firstName + ' ' + lastName;
} else {
return firstName;
}
}
let result1 = buildName('Steve'); // 'Steve'
let result2 = buildName('Steve', 'Hartzog'); // 'Steve Hartzog'
// Compiler error, too many parameters
let result3 = buildName('Steve', 'Hartzog', 'Jr.');
Generics
function identity<T>(arg: T): T {
return arg;
}
let output = identity("myString"); // 'string'
let output2 = identity(13); // 'number'
Enums
enum CardSuit {
Clubs,
Diamonds,
Hearts,
Spades
}
// Sample usage
var card = CardSuit.Clubs;
switch (myCard.suit) {
case CardSuit.Clubs:
console.log(CardSuit.Clubs);
break;
otherwise:
console.log('Not a club.');
}
Class Extensions
- Access Modifiers
- Interfaces
- Namespaces
class Person {
constructor(name) {
this.name = name;
}
greet() {
return 'My name is ' + this.name;
}
}
var annabelle = new Person('Annabelle');
console.log(annabelle.greet());
// > My name is Annabelle
class Person {
constructor(public name: string) { }
greet(): string {
return 'My name is ' + this.name;
}
}
var annabelle = new Person('Annabelle');
console.log(annabelle.greet());
// > My name is Annabelle
Class
ES6
TypeScript
Access Modifiers
// JavaScript Revealing Module Pattern
class EpicRide () extends Chevrolet {
let myVector = { };
vectorProperty(vectorMovement) {};
return {
direction: myVector;
drive() {};
}
}
// TypeScript
class EpicRide () extends Chevrolet {
private myVector: Vector = { }
private move(movement: Vector): Void {};
public direction: myVector;
public drive() {};
}
Interfaces
interface Point {
x: number;
y: number;
}
class Line {
constructor(start: Point, end: Point) { }
length(): Number { }
}
var start: Point;
var end: Point;
start.[x, y] = { 13, 3 };
start.y = 3;
end.x = 26
end.y = 6;
var myLine = new Line(start, end);
var myLineLength: Number = myLine.length(); // 13.34
Sandbox
Namespaces
- aka Internal Modules
- Reduce global footprint
- Open to be extended
- No Helper libraries required
// SNI.Utilities
// utilities.ts
import truncate from 'truncate';
import moreText from 'moreText';
namespace Strings {
export Truncate = truncate;
export MoreText from moreText;
}
export Config = function(config: object) {
// Strings default configs are set here.
truncate.config(config.truncate);
moreText.config(config.moreText);
//... additional utility configs here
}
Namespaces
// SNI
// sni.ts
import ads from 'ads'; // from ads team.
import analytics from 'analytics'; // from analytics team.
import video from 'video'; // from video team.
import utilities from 'utilities';
export Ads = ads;
export Analytics = analytics;
export Video = video;
export Utilities = utilities;
export Config = function (config: object) {
// Default configs are set here.
utilities.config(config.utilities);
analytics.config(config.analytics);
//... additional configs here
}
Namespaces
// app.ts
import SNI from 'sni';
import { config } from 'package.json';
// config all SNI namespace scripts
SNI.Config(config);
// Specific commands for any items in the SNI namespace
SNI.Ads.Start();
SNI.Analytics.Engage();
// Using the namespace truncate utility
let outputString = SNI.Utilities.Strings.Truncate(someValue);
How to install TypeScript?
- Install Node.js
- Install TypeScript by running:
npm install -g typescript
As IDE you can use Visual Studio Code https://code.visualstudio.com/
Summary
- As open as JavaScript.
- It IS ES2015, PLUS.
- Smaller, simpler output than babel.
- Advantages at scale.
- Helps catch bugs at design time.
- Custom Code Completion.
- Easy to integrate into existing build.
- Plugins for all dev environments.
- Simple to convert.
- Java is strongly typed, and now JS can be too.
Useful links
http://www.typescriptlang.org/ TypeScript
https://github.com/Microsoft/TypeScript/wiki Wiki
https://github.com/Microsoft/TypeScript/blob/master/doc/spec.md Specification
http://www.typescriptlang.org/Tutorial Tutorial
http://www.typescriptlang.org/Handbook Handbook
http://www.typescriptlang.org/Playground Playground
https://basarat.gitbooks.io/typescript/ TypeScript Deep Dive
http://blog.teamtreehouse.com/getting-started-typescript Getting Started with TypeScript
https://uptodate.frontendrescue.org/ HOW TO KEEP UP TO DATE ON Front-end
http://ipestov.com/hardcore-javascript-or-power-of-30-lines/ Hardcore JavaScript or Power of 30 lines
https://habrahabr.ru/company/it-grad/blog/275673/ Подборка: Более 800 ресурсов для front-end-разработчиков
THANKS FOR YOUR ATTENTION
TypeScript
TypeScript Old
By Dima Pikulin
TypeScript Old
- 1,144