SlideShare ist ein Scribd-Unternehmen logo
1 von 35
TYPESCRIPT TIPS
& TRICKS
Ori Calvo, 2017
oric@trainologic.com
https://trainologic.com
2
Objectives
© 2017 Ori Calvo
2
 Cover all the “good to know” details about
Typescript
 This is not an introduction session

3
The Challenge
© 2017 Ori Calvo
3
 Write today modern JavaScript code
 Even before browsers support that
 Solution: Compiler ESX  ES5
 Alternatives
 Typescript
 Babel
 CoffeeScript
 Traceur
4
Getting Started
© 2017 Ori Calvo
4
 npm install typescript
 Write some Typescript code
 Compile it with node_modules/.bin/tsc
 Run the generated JavaScript
 Use source map to debug the TypeScript
5
Good to Know
© 2017 Ori Calvo
5
Partial typeDecoratorsBarrelHow does import/export
work
Down-level support for
async/await
Down-level
generator
support
User defined type
guard
union/intersecti
on type
String EnumsCreate NPM package
--initstrictNullChecksstrict master
option
Generic parameter defaultModule augmentations
--declarationTyped map using
object
object typeMixincheckJs & allowJs
noImplicitAnyUntyped importstslibObject spread & restkeyof
Return value
from ctor
Configuration
Inheritance
--alwaysStrictType guardsNon null assertion
nevertype of thisGlob Supportpaths--traceResolution
Wildcard
module name
script vs. module--lib--noUnusedXXXWhy use target es5 with
module es6
Trailing commas
6
script vs. module
© 2017 Ori Calvo
6
 Only files which use the import/export syntax
are considered modules
 Other are considered “plain” scripts
 Module does not pollute the global scope
 Script does
7
script vs. module
© 2017 Ori Calvo
7
 Below code does not work
 Remove the export keyword and code
compiles successfully
export function xxx() {
}
interface Contact {
id: number;
name: string;
}
var x: Contact = {
id: 1,
name: "Ori",
};
8
import/export
© 2017 Ori Calvo
8
export function run() {
console.log("run");
}
import {run} from "./module1";
run();
import * as module1 from "./module1";
module1.run();
9
import/export
© 2017 Ori Calvo
9
 Part of ECMAScript 2015
 No easy way to support under ES5
 Must select a module “standard”
 amd
 commonjs
 umd
 es2015
10
import/export
© 2017 Ori Calvo
10
 Most browsers do not supports import/export
 Coming Chrome 62 will
 Therefore, must use a module loader
 Webpack
 Rollup
 Fusebox
 SystemJS
11
Barrel
© 2017 Ori Calvo
11
 Rollup exports from several modules into a
single convenient module
12
async/await
© 2017 Ori Calvo
12
function delay(ms) {
return new Promise(function(resolve) {
setTimeout(function() {
resolve();
}, ms);
});
}
async function run() {
await delay(500);
console.log("AFTER");
}
13
async/await
© 2017 Ori Calvo
13
 Part of ECMAScript 2017
 Allow for easier implementation of
asynchronous functions
 Is supported for down-level browsers too
 Debugging is challanging
14
Decorator
© 2017 Ori Calvo
14
 Attach metadata to methods/classes
 Like C# attribute
 Java annotation
 Can intercept function invocation
15
Decorator
© 2017 Ori Calvo
15
class Contact {
@Profile()
run() {
console.log("run");
}
} function Profile() {
return function(target,propertyKey: string, descriptor: PropertyDescriptor) {
const original = target[propertyKey];
target[propertyKey] = function() {
console.log("BEFORE");
const retVal = original.apply(this, arguments);
console.log("AFTER");
return retVal;
}
return target;
}
}
16
Create NPM package
© 2017 Ori Calvo
16
 Enable declaration option
 Use es2015 module settings
 Bundle all files into UMD format
 Rollup can help
 Add package.json
 main option inside package.json should point
to the UMD bundle
 npm publish
17
String Enums
© 2017 Ori Calvo
17
 Enums can now be of type string
enum Color {
red = "Red",
green = "Green",
blue = "Blue",
}
const c: Color = Color.red;
var Color;
(function (Color) {
Color["red"] = "Red";
Color["green"] = "Green";
Color["blue"] = "Blue";
})(Color || (Color = {}));
18
Union Type
© 2017 Ori Calvo
18
 Create a new type which one of the specified
interface A {
id: number,
}
interface B {
name: string,
}
type C = A | B;
const c1: C = {
id: 1,
};
const c2: C = {
name: "Ori",
};
19
Intersection Type
© 2017 Ori Calvo
19
 Define new type which has properties of all the
others
interface A {
id: number,
}
interface B {
name: string,
}
type C = A & B;
const c1: C = {
id: 1,
name: "Ori",
};
20
Object.assign
© 2017 Ori Calvo
20
 Using previous syntax we can now define
Object.assign in a type safe way
interface ObjectConstructor {
assign<T, U>(target: T, source: U): T & U;
assign<T, U, V>(target: T, source1: U, source2: V): T & U & V;
assign<T, U, V, W>(target: T, source1: U, source2: V, source3: W): T & U & V & W;
}
21
Type Guard
© 2017 Ori Calvo
21
 The following compiles successfully
class A {
}
class B extends A {
run() {
}
}
function doSomething(a: A) {
if(a instanceof B) {
a.run();
}
}
22
Challenge
© 2017 Ori Calvo
22
 However, the following does not compile
successfullyclass A {
}
class B extends A {
run() {
}
}
function isB(a: A) {
return a instanceof B;
}
function doSomething(a: A) {
if(isB(a)) {
a.run();
}
}
Property
'run' does
not exist on
type 'A'.
23
User Type Guard
© 2017 Ori Calvo
23
 We can fix that
class A {
}
class B extends A {
run() {
}
}
function isB(a: A): a is B {
return a instanceof B;
}
function doSomething(a: A) {
if(isB(a)) {
a.run();
}
}
24
Class Augmentation
© 2017 Ori Calvo
24
 An interface can extend existing class
class A {
run() {
}
}
interface A {
doSomething();
}
function main() {
const a = new A();
a.doSomething();
}
main();
25
Module Augmentation
© 2017 Ori Calvo
25
 Extend a class exported from a module
export class A {
run() {
}
}
module1
import {A} from "./module1";
declare module "./module1" {
interface A {
doSomething();
}
}
function main() {
const a = new A();
a.doSomething();
}
Applicatio
n code
26
Null Checks
© 2017 Ori Calvo
26
 The following does compile successfully
class A {
run() {
}
}
function run(a: A) {
a.run();
}
function main() {
run(null);
}
27
--strictNullChecks
© 2017 Ori Calvo
27
 If on (default is off), the compiler assume that
any type is not assignable with null or
undefined
 Now, the following code does not compile
{
"compilerOptions": {
"strictNullChecks": true
}
}
function main() {
run(null);
}
28
Allow null
© 2017 Ori Calvo
28
class A {
run() {
}
}
function run(a: A|null) {
if(a) {
a.run();
}
}
function main() {
run(null);
}
Without the if
the error
“object is
possibly null”
is reported
29
--allowJs
© 2017 Ori Calvo
29
 Tells the Typescript compiler to allow import of
a JS file
 The JS file will be verified
 But only for general syntax errors
 Type safe errors are not reported
 import/export will be converted to the specified
module system
30
--checkJs
© 2017 Ori Calvo
30
 Tells Typescript compiler to verify Type checks
as much as it can
 Sending parameters to a function
 Types are calculated based on initialization
 Can use JSDoc to annotate code with types
 For example,
function g(/** @type{string} */ a) {
a = 12;
}
31
Mixin
© 2017 Ori Calvo
31
 Create a new class out of an existing one and
add some “features” to it
class A {
constructor(name: string) {
}
}
type Constructor<T> = new(...args: any[]) => T;
function createClass<T extends Constructor<{}>>(Base: T, id) {
return class extends Base {
id: number = id;
}
}
var B = createClass(A, 5);
var b = new B("Ori");
console.log(b.id);
32
Typed map using object
© 2017 Ori Calvo
32
class Point {
constructor(private x: number, private y: number) {
}
}
const map: {[key: string]: Point} = {};
map["abc"] = new Point(5, 10);
33
keyof
© 2017 Ori Calvo
33
interface Person {
id: number;
}
type K1 = keyof Person; // id
function get<T, K extends keyof T>(obj: T, name: K): T[K] {
return obj[name];
}
var x: Person = {id:5};
get(x, "id");
34
Partial
© 2017 Ori Calvo
34
interface Person {
id: number;
name: string;
}
type PartialPerson = Partial<Person>;
const x: PartialPerson = {
id: 1,
};
THANK YOU
Ori Calvo, 2017
oric@trainologic.com
https://trainologic.com

Weitere ähnliche Inhalte

Was ist angesagt?

A Deeper look into Javascript Basics
A Deeper look into Javascript BasicsA Deeper look into Javascript Basics
A Deeper look into Javascript BasicsMindfire Solutions
 
TypeScript: coding JavaScript without the pain
TypeScript: coding JavaScript without the painTypeScript: coding JavaScript without the pain
TypeScript: coding JavaScript without the painSander Mak (@Sander_Mak)
 
TypeScript introduction to scalable javascript application
TypeScript introduction to scalable javascript applicationTypeScript introduction to scalable javascript application
TypeScript introduction to scalable javascript applicationAndrea Paciolla
 
Introduction to Javascript
Introduction to JavascriptIntroduction to Javascript
Introduction to JavascriptAmit Tyagi
 
Type script, for dummies
Type script, for dummiesType script, for dummies
Type script, for dummiessantiagoaguiar
 
JavaScript 101
JavaScript 101JavaScript 101
JavaScript 101ygv2000
 
Introduction to Dart
Introduction to DartIntroduction to Dart
Introduction to DartRamesh Nair
 
JavaScript Basics and Best Practices - CC FE & UX
JavaScript Basics and Best Practices - CC FE & UXJavaScript Basics and Best Practices - CC FE & UX
JavaScript Basics and Best Practices - CC FE & UXJWORKS powered by Ordina
 
Javascript session 01 - Introduction to Javascript
Javascript session 01 - Introduction to JavascriptJavascript session 01 - Introduction to Javascript
Javascript session 01 - Introduction to JavascriptLivingston Samuel
 
Typescript: enjoying large scale browser development
Typescript: enjoying large scale browser developmentTypescript: enjoying large scale browser development
Typescript: enjoying large scale browser developmentJoost de Vries
 
Javascript Basics
Javascript BasicsJavascript Basics
Javascript Basicsmsemenistyi
 
A Re-Introduction to JavaScript
A Re-Introduction to JavaScriptA Re-Introduction to JavaScript
A Re-Introduction to JavaScriptSimon Willison
 
JavaScript Programming
JavaScript ProgrammingJavaScript Programming
JavaScript ProgrammingSehwan Noh
 
BarcelonaJUG2016: walkmod: how to run and design code transformations
BarcelonaJUG2016: walkmod: how to run and design code transformationsBarcelonaJUG2016: walkmod: how to run and design code transformations
BarcelonaJUG2016: walkmod: how to run and design code transformationswalkmod
 
Fundamental JavaScript [UTC, March 2014]
Fundamental JavaScript [UTC, March 2014]Fundamental JavaScript [UTC, March 2014]
Fundamental JavaScript [UTC, March 2014]Aaron Gustafson
 

Was ist angesagt? (20)

A Deeper look into Javascript Basics
A Deeper look into Javascript BasicsA Deeper look into Javascript Basics
A Deeper look into Javascript Basics
 
TypeScript: coding JavaScript without the pain
TypeScript: coding JavaScript without the painTypeScript: coding JavaScript without the pain
TypeScript: coding JavaScript without the pain
 
TypeScript introduction to scalable javascript application
TypeScript introduction to scalable javascript applicationTypeScript introduction to scalable javascript application
TypeScript introduction to scalable javascript application
 
JavaScript Basics
JavaScript BasicsJavaScript Basics
JavaScript Basics
 
Introduction to Javascript
Introduction to JavascriptIntroduction to Javascript
Introduction to Javascript
 
Type script, for dummies
Type script, for dummiesType script, for dummies
Type script, for dummies
 
JavaScript 101
JavaScript 101JavaScript 101
JavaScript 101
 
Introduction to Dart
Introduction to DartIntroduction to Dart
Introduction to Dart
 
JavaScript Basics and Best Practices - CC FE & UX
JavaScript Basics and Best Practices - CC FE & UXJavaScript Basics and Best Practices - CC FE & UX
JavaScript Basics and Best Practices - CC FE & UX
 
Basics of JavaScript
Basics of JavaScriptBasics of JavaScript
Basics of JavaScript
 
Javascript session 01 - Introduction to Javascript
Javascript session 01 - Introduction to JavascriptJavascript session 01 - Introduction to Javascript
Javascript session 01 - Introduction to Javascript
 
Typescript: enjoying large scale browser development
Typescript: enjoying large scale browser developmentTypescript: enjoying large scale browser development
Typescript: enjoying large scale browser development
 
Javascript Basics
Javascript BasicsJavascript Basics
Javascript Basics
 
A Re-Introduction to JavaScript
A Re-Introduction to JavaScriptA Re-Introduction to JavaScript
A Re-Introduction to JavaScript
 
Lecture 5 javascript
Lecture 5 javascriptLecture 5 javascript
Lecture 5 javascript
 
Javascript
JavascriptJavascript
Javascript
 
Introduction to JavaScript Basics.
Introduction to JavaScript Basics.Introduction to JavaScript Basics.
Introduction to JavaScript Basics.
 
JavaScript Programming
JavaScript ProgrammingJavaScript Programming
JavaScript Programming
 
BarcelonaJUG2016: walkmod: how to run and design code transformations
BarcelonaJUG2016: walkmod: how to run and design code transformationsBarcelonaJUG2016: walkmod: how to run and design code transformations
BarcelonaJUG2016: walkmod: how to run and design code transformations
 
Fundamental JavaScript [UTC, March 2014]
Fundamental JavaScript [UTC, March 2014]Fundamental JavaScript [UTC, March 2014]
Fundamental JavaScript [UTC, March 2014]
 

Andere mochten auch

TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript IntroductionDmitry Sheiko
 
TypeScript Seminar
TypeScript SeminarTypeScript Seminar
TypeScript SeminarHaim Michael
 
TypeScript: Un lenguaje aburrido para programadores torpes y tristes
TypeScript: Un lenguaje aburrido para programadores torpes y tristesTypeScript: Un lenguaje aburrido para programadores torpes y tristes
TypeScript: Un lenguaje aburrido para programadores torpes y tristesMicael Gallego
 
Angular 2 - Typescript
Angular 2  - TypescriptAngular 2  - Typescript
Angular 2 - TypescriptNathan Krasney
 
Power Leveling your TypeScript
Power Leveling your TypeScriptPower Leveling your TypeScript
Power Leveling your TypeScriptOffirmo
 
TypeScript: особенности разработки / Александр Майоров (Tutu.ru)
TypeScript: особенности разработки / Александр Майоров (Tutu.ru)TypeScript: особенности разработки / Александр Майоров (Tutu.ru)
TypeScript: особенности разработки / Александр Майоров (Tutu.ru)Ontico
 
Typescript Fundamentals
Typescript FundamentalsTypescript Fundamentals
Typescript FundamentalsSunny Sharma
 
Александр Русаков - TypeScript 2 in action
Александр Русаков - TypeScript 2 in actionАлександр Русаков - TypeScript 2 in action
Александр Русаков - TypeScript 2 in actionMoscowJS
 
«Typescript: кому нужна строгая типизация?», Григорий Петров, MoscowJS 21
«Typescript: кому нужна строгая типизация?», Григорий Петров, MoscowJS 21«Typescript: кому нужна строгая типизация?», Григорий Петров, MoscowJS 21
«Typescript: кому нужна строгая типизация?», Григорий Петров, MoscowJS 21MoscowJS
 
TypeScript - Silver Bullet for the Full-stack Developers
TypeScript - Silver Bullet for the Full-stack DevelopersTypeScript - Silver Bullet for the Full-stack Developers
TypeScript - Silver Bullet for the Full-stack DevelopersRutenis Turcinas
 
Introducing type script
Introducing type scriptIntroducing type script
Introducing type scriptRemo Jansen
 
TypeScript: Angular's Secret Weapon
TypeScript: Angular's Secret WeaponTypeScript: Angular's Secret Weapon
TypeScript: Angular's Secret WeaponLaurent Duveau
 
TypeScript for Java Developers
TypeScript for Java DevelopersTypeScript for Java Developers
TypeScript for Java DevelopersYakov Fain
 

Andere mochten auch (20)

TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript Introduction
 
TypeScript Seminar
TypeScript SeminarTypeScript Seminar
TypeScript Seminar
 
TypeScript
TypeScriptTypeScript
TypeScript
 
TypeScript: Un lenguaje aburrido para programadores torpes y tristes
TypeScript: Un lenguaje aburrido para programadores torpes y tristesTypeScript: Un lenguaje aburrido para programadores torpes y tristes
TypeScript: Un lenguaje aburrido para programadores torpes y tristes
 
Angular 2 - Typescript
Angular 2  - TypescriptAngular 2  - Typescript
Angular 2 - Typescript
 
Power Leveling your TypeScript
Power Leveling your TypeScriptPower Leveling your TypeScript
Power Leveling your TypeScript
 
TypeScript: особенности разработки / Александр Майоров (Tutu.ru)
TypeScript: особенности разработки / Александр Майоров (Tutu.ru)TypeScript: особенности разработки / Александр Майоров (Tutu.ru)
TypeScript: особенности разработки / Александр Майоров (Tutu.ru)
 
Typescript Fundamentals
Typescript FundamentalsTypescript Fundamentals
Typescript Fundamentals
 
Александр Русаков - TypeScript 2 in action
Александр Русаков - TypeScript 2 in actionАлександр Русаков - TypeScript 2 in action
Александр Русаков - TypeScript 2 in action
 
TypeScript
TypeScriptTypeScript
TypeScript
 
«Typescript: кому нужна строгая типизация?», Григорий Петров, MoscowJS 21
«Typescript: кому нужна строгая типизация?», Григорий Петров, MoscowJS 21«Typescript: кому нужна строгая типизация?», Григорий Петров, MoscowJS 21
«Typescript: кому нужна строгая типизация?», Григорий Петров, MoscowJS 21
 
TypeScript - Silver Bullet for the Full-stack Developers
TypeScript - Silver Bullet for the Full-stack DevelopersTypeScript - Silver Bullet for the Full-stack Developers
TypeScript - Silver Bullet for the Full-stack Developers
 
Typescript
TypescriptTypescript
Typescript
 
TypeScript Overview
TypeScript OverviewTypeScript Overview
TypeScript Overview
 
Introducing type script
Introducing type scriptIntroducing type script
Introducing type script
 
TypeScript: Angular's Secret Weapon
TypeScript: Angular's Secret WeaponTypeScript: Angular's Secret Weapon
TypeScript: Angular's Secret Weapon
 
TypeScript - An Introduction
TypeScript - An IntroductionTypeScript - An Introduction
TypeScript - An Introduction
 
TypeScript for Java Developers
TypeScript for Java DevelopersTypeScript for Java Developers
TypeScript for Java Developers
 
TypeScript Presentation
TypeScript PresentationTypeScript Presentation
TypeScript Presentation
 
Typescript ppt
Typescript pptTypescript ppt
Typescript ppt
 

Ähnlich wie Typescript tips & tricks

Introduction to the New Asynchronous API in the .NET Driver
Introduction to the New Asynchronous API in the .NET DriverIntroduction to the New Asynchronous API in the .NET Driver
Introduction to the New Asynchronous API in the .NET DriverMongoDB
 
Typescript language extension of java script
Typescript language extension of java scriptTypescript language extension of java script
Typescript language extension of java scriptmichaelaaron25322
 
Better Open Source Enterprise C++ Web Services
Better Open Source Enterprise C++ Web ServicesBetter Open Source Enterprise C++ Web Services
Better Open Source Enterprise C++ Web ServicesWSO2
 
The First C# Project Analyzed
The First C# Project AnalyzedThe First C# Project Analyzed
The First C# Project AnalyzedPVS-Studio
 
Let's play with adf 3.0
Let's play with adf 3.0Let's play with adf 3.0
Let's play with adf 3.0Eugenio Romano
 
Of complicacy of programming, or won't C# save us?
Of complicacy of programming, or won't C# save us?Of complicacy of programming, or won't C# save us?
Of complicacy of programming, or won't C# save us?PVS-Studio
 
Front End Development: The Important Parts
Front End Development: The Important PartsFront End Development: The Important Parts
Front End Development: The Important PartsSergey Bolshchikov
 
CodeMash - Building Rich Apps with Groovy SwingBuilder
CodeMash - Building Rich Apps with Groovy SwingBuilderCodeMash - Building Rich Apps with Groovy SwingBuilder
CodeMash - Building Rich Apps with Groovy SwingBuilderAndres Almiray
 
.gradle 파일 정독해보기
.gradle 파일 정독해보기.gradle 파일 정독해보기
.gradle 파일 정독해보기경주 전
 
Parse cloud code
Parse cloud codeParse cloud code
Parse cloud code維佋 唐
 
Java script Techniques Part I
Java script Techniques Part IJava script Techniques Part I
Java script Techniques Part ILuis Atencio
 
A New Chapter of Data Processing with CDK
A New Chapter of Data Processing with CDKA New Chapter of Data Processing with CDK
A New Chapter of Data Processing with CDKShu-Jeng Hsieh
 
Cocoa for Web Developers
Cocoa for Web DevelopersCocoa for Web Developers
Cocoa for Web Developersgeorgebrock
 
How to create an Angular builder
How to create an Angular builderHow to create an Angular builder
How to create an Angular builderMaurizio Vitale
 
Angular for Java Enterprise Developers: Oracle Code One 2018
Angular for Java Enterprise Developers: Oracle Code One 2018Angular for Java Enterprise Developers: Oracle Code One 2018
Angular for Java Enterprise Developers: Oracle Code One 2018Loiane Groner
 
Smoothing Your Java with DSLs
Smoothing Your Java with DSLsSmoothing Your Java with DSLs
Smoothing Your Java with DSLsintelliyole
 

Ähnlich wie Typescript tips & tricks (20)

Introduction to the New Asynchronous API in the .NET Driver
Introduction to the New Asynchronous API in the .NET DriverIntroduction to the New Asynchronous API in the .NET Driver
Introduction to the New Asynchronous API in the .NET Driver
 
Typescript language extension of java script
Typescript language extension of java scriptTypescript language extension of java script
Typescript language extension of java script
 
Let's migrate to Swift 3.0
Let's migrate to Swift 3.0Let's migrate to Swift 3.0
Let's migrate to Swift 3.0
 
Better Open Source Enterprise C++ Web Services
Better Open Source Enterprise C++ Web ServicesBetter Open Source Enterprise C++ Web Services
Better Open Source Enterprise C++ Web Services
 
Objective c intro (1)
Objective c intro (1)Objective c intro (1)
Objective c intro (1)
 
The First C# Project Analyzed
The First C# Project AnalyzedThe First C# Project Analyzed
The First C# Project Analyzed
 
Let's play with adf 3.0
Let's play with adf 3.0Let's play with adf 3.0
Let's play with adf 3.0
 
Of complicacy of programming, or won't C# save us?
Of complicacy of programming, or won't C# save us?Of complicacy of programming, or won't C# save us?
Of complicacy of programming, or won't C# save us?
 
C# 6.0
C# 6.0C# 6.0
C# 6.0
 
Front End Development: The Important Parts
Front End Development: The Important PartsFront End Development: The Important Parts
Front End Development: The Important Parts
 
CodeMash - Building Rich Apps with Groovy SwingBuilder
CodeMash - Building Rich Apps with Groovy SwingBuilderCodeMash - Building Rich Apps with Groovy SwingBuilder
CodeMash - Building Rich Apps with Groovy SwingBuilder
 
.gradle 파일 정독해보기
.gradle 파일 정독해보기.gradle 파일 정독해보기
.gradle 파일 정독해보기
 
Day 1
Day 1Day 1
Day 1
 
Parse cloud code
Parse cloud codeParse cloud code
Parse cloud code
 
Java script Techniques Part I
Java script Techniques Part IJava script Techniques Part I
Java script Techniques Part I
 
A New Chapter of Data Processing with CDK
A New Chapter of Data Processing with CDKA New Chapter of Data Processing with CDK
A New Chapter of Data Processing with CDK
 
Cocoa for Web Developers
Cocoa for Web DevelopersCocoa for Web Developers
Cocoa for Web Developers
 
How to create an Angular builder
How to create an Angular builderHow to create an Angular builder
How to create an Angular builder
 
Angular for Java Enterprise Developers: Oracle Code One 2018
Angular for Java Enterprise Developers: Oracle Code One 2018Angular for Java Enterprise Developers: Oracle Code One 2018
Angular for Java Enterprise Developers: Oracle Code One 2018
 
Smoothing Your Java with DSLs
Smoothing Your Java with DSLsSmoothing Your Java with DSLs
Smoothing Your Java with DSLs
 

Kürzlich hochgeladen

Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprisepreethippts
 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...confluent
 
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Cizo Technology Services
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作qr0udbr0
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtimeandrehoraa
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024StefanoLambiase
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmSujith Sukumaran
 
VK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web DevelopmentVK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web Developmentvyaparkranti
 
Machine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringMachine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringHironori Washizaki
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Andreas Granig
 
UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxUI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxAndreas Kunz
 
Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Rob Geurden
 
Comparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfComparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfDrew Moseley
 
Xen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfXen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfStefano Stabellini
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEEVICTOR MAESTRE RAMIREZ
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureDinusha Kumarasiri
 
Cyber security and its impact on E commerce
Cyber security and its impact on E commerceCyber security and its impact on E commerce
Cyber security and its impact on E commercemanigoyal112
 
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Matt Ray
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...OnePlan Solutions
 

Kürzlich hochgeladen (20)

Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprise
 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
 
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作
 
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort ServiceHot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtime
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalm
 
VK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web DevelopmentVK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web Development
 
Machine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringMachine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their Engineering
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024
 
UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxUI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
 
Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...
 
Comparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfComparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdf
 
Xen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfXen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdf
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEE
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with Azure
 
Cyber security and its impact on E commerce
Cyber security and its impact on E commerceCyber security and its impact on E commerce
Cyber security and its impact on E commerce
 
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
 

Typescript tips & tricks

  • 1. TYPESCRIPT TIPS & TRICKS Ori Calvo, 2017 oric@trainologic.com https://trainologic.com
  • 2. 2 Objectives © 2017 Ori Calvo 2  Cover all the “good to know” details about Typescript  This is not an introduction session 
  • 3. 3 The Challenge © 2017 Ori Calvo 3  Write today modern JavaScript code  Even before browsers support that  Solution: Compiler ESX  ES5  Alternatives  Typescript  Babel  CoffeeScript  Traceur
  • 4. 4 Getting Started © 2017 Ori Calvo 4  npm install typescript  Write some Typescript code  Compile it with node_modules/.bin/tsc  Run the generated JavaScript  Use source map to debug the TypeScript
  • 5. 5 Good to Know © 2017 Ori Calvo 5 Partial typeDecoratorsBarrelHow does import/export work Down-level support for async/await Down-level generator support User defined type guard union/intersecti on type String EnumsCreate NPM package --initstrictNullChecksstrict master option Generic parameter defaultModule augmentations --declarationTyped map using object object typeMixincheckJs & allowJs noImplicitAnyUntyped importstslibObject spread & restkeyof Return value from ctor Configuration Inheritance --alwaysStrictType guardsNon null assertion nevertype of thisGlob Supportpaths--traceResolution Wildcard module name script vs. module--lib--noUnusedXXXWhy use target es5 with module es6 Trailing commas
  • 6. 6 script vs. module © 2017 Ori Calvo 6  Only files which use the import/export syntax are considered modules  Other are considered “plain” scripts  Module does not pollute the global scope  Script does
  • 7. 7 script vs. module © 2017 Ori Calvo 7  Below code does not work  Remove the export keyword and code compiles successfully export function xxx() { } interface Contact { id: number; name: string; } var x: Contact = { id: 1, name: "Ori", };
  • 8. 8 import/export © 2017 Ori Calvo 8 export function run() { console.log("run"); } import {run} from "./module1"; run(); import * as module1 from "./module1"; module1.run();
  • 9. 9 import/export © 2017 Ori Calvo 9  Part of ECMAScript 2015  No easy way to support under ES5  Must select a module “standard”  amd  commonjs  umd  es2015
  • 10. 10 import/export © 2017 Ori Calvo 10  Most browsers do not supports import/export  Coming Chrome 62 will  Therefore, must use a module loader  Webpack  Rollup  Fusebox  SystemJS
  • 11. 11 Barrel © 2017 Ori Calvo 11  Rollup exports from several modules into a single convenient module
  • 12. 12 async/await © 2017 Ori Calvo 12 function delay(ms) { return new Promise(function(resolve) { setTimeout(function() { resolve(); }, ms); }); } async function run() { await delay(500); console.log("AFTER"); }
  • 13. 13 async/await © 2017 Ori Calvo 13  Part of ECMAScript 2017  Allow for easier implementation of asynchronous functions  Is supported for down-level browsers too  Debugging is challanging
  • 14. 14 Decorator © 2017 Ori Calvo 14  Attach metadata to methods/classes  Like C# attribute  Java annotation  Can intercept function invocation
  • 15. 15 Decorator © 2017 Ori Calvo 15 class Contact { @Profile() run() { console.log("run"); } } function Profile() { return function(target,propertyKey: string, descriptor: PropertyDescriptor) { const original = target[propertyKey]; target[propertyKey] = function() { console.log("BEFORE"); const retVal = original.apply(this, arguments); console.log("AFTER"); return retVal; } return target; } }
  • 16. 16 Create NPM package © 2017 Ori Calvo 16  Enable declaration option  Use es2015 module settings  Bundle all files into UMD format  Rollup can help  Add package.json  main option inside package.json should point to the UMD bundle  npm publish
  • 17. 17 String Enums © 2017 Ori Calvo 17  Enums can now be of type string enum Color { red = "Red", green = "Green", blue = "Blue", } const c: Color = Color.red; var Color; (function (Color) { Color["red"] = "Red"; Color["green"] = "Green"; Color["blue"] = "Blue"; })(Color || (Color = {}));
  • 18. 18 Union Type © 2017 Ori Calvo 18  Create a new type which one of the specified interface A { id: number, } interface B { name: string, } type C = A | B; const c1: C = { id: 1, }; const c2: C = { name: "Ori", };
  • 19. 19 Intersection Type © 2017 Ori Calvo 19  Define new type which has properties of all the others interface A { id: number, } interface B { name: string, } type C = A & B; const c1: C = { id: 1, name: "Ori", };
  • 20. 20 Object.assign © 2017 Ori Calvo 20  Using previous syntax we can now define Object.assign in a type safe way interface ObjectConstructor { assign<T, U>(target: T, source: U): T & U; assign<T, U, V>(target: T, source1: U, source2: V): T & U & V; assign<T, U, V, W>(target: T, source1: U, source2: V, source3: W): T & U & V & W; }
  • 21. 21 Type Guard © 2017 Ori Calvo 21  The following compiles successfully class A { } class B extends A { run() { } } function doSomething(a: A) { if(a instanceof B) { a.run(); } }
  • 22. 22 Challenge © 2017 Ori Calvo 22  However, the following does not compile successfullyclass A { } class B extends A { run() { } } function isB(a: A) { return a instanceof B; } function doSomething(a: A) { if(isB(a)) { a.run(); } } Property 'run' does not exist on type 'A'.
  • 23. 23 User Type Guard © 2017 Ori Calvo 23  We can fix that class A { } class B extends A { run() { } } function isB(a: A): a is B { return a instanceof B; } function doSomething(a: A) { if(isB(a)) { a.run(); } }
  • 24. 24 Class Augmentation © 2017 Ori Calvo 24  An interface can extend existing class class A { run() { } } interface A { doSomething(); } function main() { const a = new A(); a.doSomething(); } main();
  • 25. 25 Module Augmentation © 2017 Ori Calvo 25  Extend a class exported from a module export class A { run() { } } module1 import {A} from "./module1"; declare module "./module1" { interface A { doSomething(); } } function main() { const a = new A(); a.doSomething(); } Applicatio n code
  • 26. 26 Null Checks © 2017 Ori Calvo 26  The following does compile successfully class A { run() { } } function run(a: A) { a.run(); } function main() { run(null); }
  • 27. 27 --strictNullChecks © 2017 Ori Calvo 27  If on (default is off), the compiler assume that any type is not assignable with null or undefined  Now, the following code does not compile { "compilerOptions": { "strictNullChecks": true } } function main() { run(null); }
  • 28. 28 Allow null © 2017 Ori Calvo 28 class A { run() { } } function run(a: A|null) { if(a) { a.run(); } } function main() { run(null); } Without the if the error “object is possibly null” is reported
  • 29. 29 --allowJs © 2017 Ori Calvo 29  Tells the Typescript compiler to allow import of a JS file  The JS file will be verified  But only for general syntax errors  Type safe errors are not reported  import/export will be converted to the specified module system
  • 30. 30 --checkJs © 2017 Ori Calvo 30  Tells Typescript compiler to verify Type checks as much as it can  Sending parameters to a function  Types are calculated based on initialization  Can use JSDoc to annotate code with types  For example, function g(/** @type{string} */ a) { a = 12; }
  • 31. 31 Mixin © 2017 Ori Calvo 31  Create a new class out of an existing one and add some “features” to it class A { constructor(name: string) { } } type Constructor<T> = new(...args: any[]) => T; function createClass<T extends Constructor<{}>>(Base: T, id) { return class extends Base { id: number = id; } } var B = createClass(A, 5); var b = new B("Ori"); console.log(b.id);
  • 32. 32 Typed map using object © 2017 Ori Calvo 32 class Point { constructor(private x: number, private y: number) { } } const map: {[key: string]: Point} = {}; map["abc"] = new Point(5, 10);
  • 33. 33 keyof © 2017 Ori Calvo 33 interface Person { id: number; } type K1 = keyof Person; // id function get<T, K extends keyof T>(obj: T, name: K): T[K] { return obj[name]; } var x: Person = {id:5}; get(x, "id");
  • 34. 34 Partial © 2017 Ori Calvo 34 interface Person { id: number; name: string; } type PartialPerson = Partial<Person>; const x: PartialPerson = { id: 1, };
  • 35. THANK YOU Ori Calvo, 2017 oric@trainologic.com https://trainologic.com