TypeScript for C# developers. Making JavaScript manageable



Similar documents
: provid.ir

TypeScript. Language Specification. Version 1.4

Java Application Developer Certificate Program Competencies

JavaScript. JavaScript: fundamentals, concepts, object model. Document Object Model. The Web Page. The window object (1/2) The document object

C++ INTERVIEW QUESTIONS

GTask Developing asynchronous applications for multi-core efficiency

Glossary of Object Oriented Terms

Programming in C# with Microsoft Visual Studio 2010

Objectif. Participant. Prérequis. Remarque. Programme. C# 3.0 Programming in the.net Framework. 1. Introduction to the.

Web Development in Java

Modern Web Development with Dart. Alan Knight Google

#820 Computer Programming 1A

Java Interview Questions and Answers

JavaScript Patterns. Stoyan Stefanov. O'REILLY' Beijing Cambridge Farnham Koln Sebastopol Tokyo

The Java Series. Java Essentials I What is Java? Basic Language Constructs. Java Essentials I. What is Java?. Basic Language Constructs Slide 1

Art of Code Front-end Web Development Training Program

PROFESSIONAL. Node.js BUILDING JAVASCRIPT-BASED SCALABLE SOFTWARE. Pedro Teixeira WILEY. John Wiley & Sons, Inc.

Computer Programming I

AP Computer Science Java Subset

CS 111 Classes I 1. Software Organization View to this point:

Fundamentals of Java Programming

Specialized Programme on Web Application Development using Open Source Tools

Java SE 8 Programming

core. Volume I - Fundamentals Seventh Edition Sun Microsystems Press A Prentice Hall Title ULB Darmstadt

MASTERTAG DEVELOPER GUIDE

Syllabus for CS 134 Java Programming

Specialized Programme on Web Application Development using Open Source Tools

Java EE Web Development Course Program

History OOP languages Year Language 1967 Simula Smalltalk

JavaScript as a compilation target Making it fast

QML and JavaScript for Native App Development

The Sun Certified Associate for the Java Platform, Standard Edition, Exam Version 1.0

Level 7. ECMAScript 5: The New Parts

Visual C# 2012 Programming

Course Title: Software Development

MA-WA1920: Enterprise iphone and ipad Programming

Tutorial on Writing Modular Programs in Scala

Modern Web Development:

opalang - Rapid & Secure Web Development

Program Analysis for JavaScript Challenges and Techniques

The Needle Programming Language

A Standardized Representation of Asynchronous Operations

CSCI 253. Object Oriented Programming (OOP) Overview. George Blankenship 1. Object Oriented Design: Java Review OOP George Blankenship.

Chapter 13 - Inheritance

Java Programming Language

Object-Oriented Design Lecture 4 CSU 370 Fall 2007 (Pucella) Tuesday, Sep 18, 2007

Computer Programming I & II*

Ajax Development with ASP.NET 2.0

Applied Internet Technology (CSCI-UA.0480) - Sample Questions

Software Construction

Android Application Development Course Program

COURSE SYLLABUS EDG 6931: Designing Integrated Media Environments 2 Educational Technology Program University of Florida

Java SE 7 Programming

Introduction to Visual Studio and C#


Dashboard Skin Tutorial. For ETS2 HTML5 Mobile Dashboard v3.0.2

Android Studio Application Development

Title: Appium Automation for Mac OS X. Created By: Prithivirajan M. Abstract. Introduction

NoSQL web apps. w/ MongoDB, Node.js, AngularJS. Dr. Gerd Jungbluth, NoSQL UG Cologne,

JavaScript: Client-Side Scripting. Chapter 6

SharePoint 2013 DEV. David Čamdžić Kompas Xnet d.o.o.

Tutorial: Building a Dojo Application using IBM Rational Application Developer Loan Payment Calculator

JavaScript: Control Statements I

First Java Programs. V. Paúl Pauca. CSC 111D Fall, Department of Computer Science Wake Forest University. Introduction to Computer Science

Programming in C# with Microsoft Visual Studio 2010

Supporting Data Set Joins in BIRT

Konzepte objektorientierter Programmierung

RARITAN VALLEY COMMUNITY COLLEGE ACADEMIC COURSE OUTLINE. CISY 105 Foundations of Computer Science

Overview. Elements of Programming Languages. Advanced constructs. Motivating inner class example

PROBLEM SOLVING SEVENTH EDITION WALTER SAVITCH UNIVERSITY OF CALIFORNIA, SAN DIEGO CONTRIBUTOR KENRICK MOCK UNIVERSITY OF ALASKA, ANCHORAGE PEARSON

Operator Overloading. Lecture 8. Operator Overloading. Running Example: Complex Numbers. Syntax. What can be overloaded. Syntax -- First Example

Java SE 7 Programming

Java SE 7 Programming

Integration of Application Business Logic and Business Rules with DSL and AOP

Interactive Data Visualization for the Web Scott Murray

Designing with Exceptions. CSE219, Computer Science III Stony Brook University

Software Testing. Definition: Testing is a process of executing a program with data, with the sole intention of finding errors in the program.

TECHNOLOGY Computer Programming II Grade: 9-12 Standard 2: Technology and Society Interaction

Intellicus Single Sign-on

Getting Started with the Internet Communications Engine

Performance Testing for Ajax Applications

Curriculum Map. Discipline: Computer Science Course: C++

Fast JavaScript in V8. The V8 JavaScript Engine. ...well almost all boats. Never use with. Never use with part 2.

Programming and Software Development CTAG Alignments

Handout 1. Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner.

MXwendler Javascript Interface Description Version 2.3

C++FA 5.1 PRACTICE MID-TERM EXAM

Principles of Object-Oriented Programming in JavaScript

Getting Started Developing JavaScript Web Apps. this = that. VT Geospatial Forum 2015

Web Programming Step by Step


Client-side Web Engineering From HTML to AJAX

OBJECT-ORIENTED JAVASCRIPT OBJECT-ORIENTED

JavaScript Introduction

Transcription:

TypeScript for C# developers Making JavaScript manageable

Agenda What is TypeScript OO in TypeScript Closure Generics Iterators Asynchronous programming Modularisation Debugging TypeScript 2

What is TypeScript A language that compiles to JavaScript, designed by Microsoft Used by Google ( Angular 2) Run in the browser and on the server ( Node JS) Provides similar OO and type safety to C# But its not C# 3

JavaScript Issues when building large scale apps No type safety No language support for modularization Encapsulation not promoted by the language Developer needs to use a variety of techniques and patterns to make it happen. Advantages Runs in browsers on many platforms Can be used to build server apps NodeJS Lots of existing frameworks 4

TypeScript and JavaScript TypeScript is a thin veneer on JavaScript providing type safety and modularisation Understand JavaScript and lots of TypeScript oddities make sense Function scope Array indexes are just properties Objects only have public fields No function overloading Later versions of JavaScript fix some of these features Block scope Property getters and setters Class 5

Using JavaScript frameworks from TypeScript DefinitelyTyped files (.ts) for all major JavaScript frameworks Provides strong typing and intelli sense for JavaScript frameworks via TypeScript Definitions found on GitHub and Nuget 6

Classes Similar to C# Class keyword Public, Private encapsulation Explicitly named Constructor method Properties as of EcmaScript 5 Conventions Private fields start with an _ Public fields start with lower case, and then camel case Methods start with lower case, and then camel case Method return type can be left to the compiler to determine 7

Primitive types For int,double,float,long use number For string use string For bool use boolean For object use any For void use void 8

Private means what? TypeScripts creates the notion of private JavaScript does not have the notion of private Objects created in TypeScript consumed via JavaScript have no privacy 9

Polymorphism Uses extends keyword to derive from class Classes and methods can be marked as abstract Use super() not base to call base type methods No need to overload constructor if simply want base type behaviour. 10

Exceptions Anything can be thrown Best practice is to throw instance of Error/derived from Error Catch blocks can t filter by type Use instanceof to get type 11

any the dynamic in TypeScript Variables marked as any behave like regular JavaScript objects No real intellisense build(options: any): string { var url: string = ""; if (options.protocol!== undefined) { url = options.protocol + "://"; url += options.path; return url; 12

Interfaces Used to describe the shape of objects Useful for passing parameters and object literal interface SuccessCallback { (data: string): void; interface AjaxOptions { url: string; verb?: string; success: SuccessCallback; class AjaxClient { call(options: AjaxOptions) { if (options.verb == undefined) { options.verb = "POST"; 13

Interfaces for methods, not quiet Delegates Interfaces used to build Function Types Type safety similar to Delegates WARNING, invoking functions this is not what you may expect. interface SearchFunc { (source: string, substring: string): boolean; 14

Overloading JavaScript does not support overloading TypeScript has a kind of overloading Assists with intellisense Many signatures One Implementation Signatures must be compatible with implementation Implementation has to examine parameters to vary behaviour createurl(options: IUrlParts): string; createurl(path:string):string; createurl(options: any): string { 15

Closures The var keyword provides method based scoping The let keyword provides block based scoping Most noticeable when using closure Two ways to define closures Anonymous functions Lambda s known as Arrow functions Arrow functions capture this Gives you same behaviour as C# Anonymous functions use normal JavaScript rules for this. 16

Generics Generic functions, classes and interfaces possible Utilises constraints similar to C# to define functionality against type arguments class Utils { public static min<t extends IComparable>(items:T[]):T { var min:t = items[0]; for (var i = 1; i < items.length; i++) { if (min.compareto(items[i]) > 0) { min = items[i]; return min; 17

Better than.net generics Sometimes hard to build generics around.net shipped types JavaScript uses prototypical inheritance Add methods to objects that have already been created interface IComparable<T> { compareto(other:t):number; interface Number extends IComparable<number> { Number.prototype.compareTo = function(rhs: number) { var lhs:number = this; if (lhs === rhs) return 0; if (lhs < rhs) return -1; return 1; 18

Iterators for in syntax iterators over properties in JavaScript/TypeScript var values = { name: 'andy', age: 21 ; for (var value in values) { console.log(value); name age var collection = [10, 20, 30]; for (var item in collection) { console.log(item); 1 2 3 19

Modern JavaScript for..of, for iteration Provides equivalent of foreach in C# Iterable<T> equivalent to IEnumerable<T> Iterator<T> equivalent to IEnumerator<T> Built in types Array,Map,Set supported var collection = [10, 20, 30]; for (var item of collection) { console.log(item); 10 20 30 20

Generators Can build custom iterators by hand Automated using the yield keyword class FibGeneratation { *getfibs(nfibs: number) { var current = 1; var prev = 0; var prevprev = 0; for (var nfib = 0; nfib < nfibs; nfib++) { yield current; prevprev = prev; prev = current; current = prev + prevprev; 21

Delegating generators Generators can delegate to other generators to combine sequences class Enumerable { *combine<t>(first:iterable<t>,second:iterable<t>){ yield* first; yield* second; var enumerable = new Enumerable(); var sequence = enumerable.combine([1,2,3],[4,5,6]); 22

Asynchronous operations with Promise<T> Built around the Promise type similar to Task<T> Promise provides fluent api to setup continuations Create the promise and provide the executor function Executor function is supplied callbacks for outcome class Async { delay(time: number):promise<any> { var executor = (resolve: (result: any) => void, reject: (error: any) => void) => { window.settimeout(() => resolve(null), time); ; var timerpromise = new Promise<any>(executor); return timerpromise; 23

Working with Promises Use fluent api to register continuations in case of Ran to completion Failure var asyncoperations = new Async(); asyncoperations.delay(2000).then(_ => { console.log( delay of 2 seconds done ); ).catch(err => { console.log( something went wrong ); ); 24

Simplified with async and await Provides similar pattern of use to that of C# Keeps code simple, async function() { var asyncoperations = new Async(); await asyncoperations.delay(2000); console.log( delay completed ); 25

And finally just remember TypeScript is JavaScript 1.3 + 2.1 =? typeof NaN =? NaN == NaN =? 26

Summary TypeScript offers type safety Encapsulation out of the box Compiles to JavaScript and so behaves like JavaScript 27