SlideShare a Scribd company logo
1 of 29
TypeScript
Basic Types
Boolean
Number
String
Array
Enum
Any
Void
Basic Types(1)
TypeScript
JavaScript
Boolean var isDone: boolean = false; var isDone = false;
Number var height: number = 6; var height = 6;
String var name: string = "bob"; var name = "bob";
name = 'smith'; name = 'smith';
Array type of the elements followed by '[]'
var list:number[] = [1, 2, 3]; var list = [1, 2, 3];
Array<elemType>
var list:Array<number> = [1, 2, 3]; *JS With
Type Annotation
Basic Types(2)
Enum 1 enum Color {Red, Green, Blue};
var c: Color = Color.Green;
Enum 2 enum Color {Red = 1, Green, Blue};
var c: Color = Color.Green;
Enum 3 enum Color {Red = 1, Green = 2, Blue = 4};
var c: Color = Color.Green;
from a numeric value to the name of that value
enum Color {Red = 1, Green, Blue};
var colorName: string = Color[2];
Basic Types(3)
Enum var Color;
enum Color {Red, Green, Blue}; (function (Color) {
Color[Color[“Red”] = 0] = “Red”;
Color[Color[“Green”] = 1] =
“Green”;
Color[Color[“Blue”] = 2] = “Blue”;
})(Color || (Color = {}));1. Color[Color[“Red”] = 0] =
“Red”;
Color[“Red”] = 0;
Color[0] = “Red”;
2. immediately executing function
(function (Color) {...})();
var a = function(Color){...};
a(Color || (Color = {}));3. var Color = {};
(function (Color)
{...})(Color);
Basic Types(4)
Any Allow you to gradually opt-in and opt-out of type-checking during compilation.
var notSure: any = 4;
notSure = "maybe a string instead";
notSure = false; // okay, definitely a boolean
var list:any[] = [1, true, "free"];
list[1] = 100;
Void function warnUser(): void {
alert("This is my warning message");
}
Interfaces(1)
One of TypeScript's core principles is that type-checking focuses on the 'shape' that values have. This is
sometimes called "duck typing" or "structural subtyping".
Start With...
using an interface
function printLabel(labelledObj: {label: string}) {
console.log(labelledObj.label);
}
var myObj = {size: 10, label: "Size 10 Object"};
printLabel(myObj);
interface LabelledValue {
label: string;
}
function printLabel(labelledObj: LabelledValue) {
console.log(labelledObj.label);
}
(JS) function printLabel(labelledObj) {
console.log(labelledObj.label);
}
Interfaces(2)
Optional Properties
function createSquare(config: SquareConfig): {color: string; area: number} {
var newSquare = {color: "white", area: 100};
if (config.color) {
newSquare.color = config.color;
}
if (config.width) {
newSquare.area = config.width * config.width;
}
return newSquare;
}
var mySquare = createSquare({color: "black"});
interface SquareConfig
{
color?: string;
width?: number;
}
Interfaces(3)
Optional Properties(JS)
function createSquare(config: SquareConfig): {color: string; area: number} {
var newSquare = {color: "white", area: 100};
if (config.color) {
newSquare.color = config.color;
}
if (config.width) {
newSquare.area = config.width * config.width;
}
return newSquare;
}
var mySquare = createSquare({color: "black"});
interface SquareConfig
{
color?: string;
width?: number;
}
Interfaces(3)
Function Types
var mySearch: SearchFunc;
mySearch = function(source: string, subString: string) {
var result = source.search(subString);
if (result == -1) {
return false;
}
else {
return true;
}
}
//mySearch = function(src: string, sub: string) {
// var result = src.search(sub);
interface SearchFunc {
(source: string, subString: string): boolean;
}
Interfaces(4)
Array Types
Dictionary
interface StringArray {
[index: number]: string;
}
var myArray: StringArray;
myArray = ["Bob", "Fred"];
interface Dictionary {
[index: string]: string;
length: number;
// error, the type of 'length' is not a subtype of the indexer
owner: string;
}
var dic: Dictionary;
dic.length: return a number
=> dic[“length”]
Interfaces(5)
Class Types - Implementing an interface
interface ClockInterface {
currentTime: Date;
}
class Clock implements ClockInterface {
currentTime: Date;
constructor(h: number, m: number) { }
}
var Clock = (function() {
function Clock(h, m)
{
}
return Clock;
})();
var a = function Clock(h, m) {
};
var b = function() {
return a;
};
var Clock = b();
Interfaces(6)
Class Types - Implementing an interface
interface ClockInterface {
currentTime: Date;
setTime(d: Date);
}
class Clock implements ClockInterface {
currentTime: Date;
setTime(d: Date) {
this.currentTime = d;
}
constructor(h: number, m: number) { }
}
var Clock = (function() {
function Clock(h, m) {
}
Clock.prototype.setTime = function(d) {
this.currentTime = d;
};
return Clock;
})();
Interfaces(7)
Class Types - Difference between static/instance side of class
You may notice that if you create an interface with a construct signature and try to create a class that implements this
interface you get an error:
This is because when a class implements an interface, only the instance side of the class is checked.
Since the constructor sits in the static side, it is not included in this check.
Instead, you would need to work with the 'static' side of the class directly.
interface ClockInterface {
new (hour: number, minute: number);
}
//Class ‘Clock’ incorrectly implements
interface ‘ClockInterface’
class Clock implements ClockInterface {
currentTime: Date;
constructor(h: number, m: number) { }
}
interface ClockStatic {
new (hour: number, minute: number);
}
class Clock {
currentTime: Date;
constructor(h: number, m: number) { }
}
var cs: ClockStatic = Clock;
var newClock = new cs(7, 30);
Interfaces(8)
Extending Interfaces
interface Shape {
color: string;
}
interface Square extends Shape {
sideLength: number;
}
var square = <Square>{};
square.color = "blue";
square.sideLength = 10;
interface Shape {
color: string;
}
interface PenStroke {
penWidth: number;
}
interface Square extends Shape, PenStroke {
sideLength: number;
}
var square = <Square>{};
square.color = "blue";
square.sideLength = 10;
square.penWidth = 5.0;var square = {};
square.color = "blue";
square.sideLength = 10;
square.penWidth = 5.0;
Interfaces(8)
Class Types - Hybrid Types
interface Counter {
(start: number): string;
interval: number;
reset(): void;
}
var c: Counter; //undefined
c(10);
c.reset();
c.interval = 5.0;
Classes(1)
Classes
class Greeter {
greeting: string;
constructor(message: string) {
this.greeting = message;
}
greet() {
return "Hello, " + this.greeting;
}
}
var greeter = new Greeter("world");
var Greeter = (function() {
function Greeter(message) {
this.greeting = message;
}
Greeter.prototype.greet = function()
{
return "Hello, " + this.greeting;
}
}
var greeter = new Greeter("world");
Classes(2)
Inheritance
var sam = new Snake("Sammy");
var tom: Animal = new Horse("Tommy");
sam.move();
tom.move(34);
class Animal {
name:string;
constructor(theName: string) { this.name = theName;
}
move(meters: number = 0) {
alert(this.name + " moved " + meters + "m.");
}
}
class Snake extends Animal {
constructor(name: string) { super(name); }
move(meters = 5) {
alert("Slithering...");
super.move(meters);
}
}
class Horse extends Animal {
constructor(name: string) { super(name); }
move(meters = 45) {
alert("Galloping...");
super.move(meters);
}
}
Classes(3)
Inheritance(JS) var Animal = (function() {
function Animal(theName) { this.name = theName; }
Amimal.prototype.move = function(meters) {
if (meters === void 0) { meters = 0; }
alert(this.name + " moved " + meters + "m.");
};
return Animal;
})();
var Snake = (function(_supper) {
__extends(Snake, _super);
function Snake(name) {
_super.call(this, name);
}
Amimal.prototype.move = function(meters) {
if (meters === void 0) { meters = 5; }
alert("Slithering...”);
_super.prototype.move.call(this, meters);
};
return Snake;
})(Animal);
Classes(4)
Private/Public modifiers - Public by default
class Animal {
private name:string;
constructor(theName: string) { this.name = theName; }
move(meters: number) {
alert(this.name + " moved " + meters + "m.");
}
}
Classes(5)
Private/Public modifiers - Understanding private
For two types to be considered compatible, if one of them has a private member, then the other must have a private
member that originated in the same declaration.
class Animal {
private name:string;
constructor(theName: string) {
this.name = theName;
}
}
class Rhino extends Animal {
constructor() { super("Rhino"); }
}
class Employee {
private name:string;
constructor(theName: string) {
this.name = theName;
}
}
var animal = new Animal("Goat");
var rhino = new Rhino();
var employee = new Employee("Bob");
animal = rhino;
animal = employee;
//error: Animal and Employee are
not compatible
Classes(6)
Private/Public modifiers - Parameter properties
Using 'private' in this way creates and initializes a private member, and similarly for 'public'.
class Animal {
constructor(private name: string) { }
move(meters: number) {
alert(this.name + " moved " + meters + "m.");
}
}
Classes(7)
Without Accessors(get/set)
class Employee {
fullName: string;
}
var employee = new Employee();
employee.fullName = "Bob Smith";
if (employee.fullName) {
alert(employee.fullName);
}
var Employee = (function () {
function Employee() {
}
return Employee;
})();
var employee = new Employee();
employee.fullName = "Bob Smith";
if (employee.fullName) {
alert(employee.fullName);
}
Classes(8)
With Accessors(get/set)
var passcode = "passcode";
class Employee {
private _fullName: string;
get fullName(): string {
return this._fullName;
}
set fullName(newName: string) {
if (passcode && passcode == "passcode") {
this._fullName = newName;
}
else {
alert("Error!");
}
}
}
var employee = new Employee();
employee.fullName = "Bob Smith";
if (employee.fullName) {
alert(employee.fullName);
}
var passcode = "passcode";
var Employee = (function () {
function Employee() {
}
Object.defineProperty(Employee.prototype, "fullName", {
get: function () {
return this._fullName;
},
set: function (newName) {
if (passcode && passcode == "passcode") {
this._fullName = newName;
}
else {
alert("Error!");
}
},
enumerable: true,
configurable: true
});
return Employee;
})();
Classes(9)
Static Properties
class Grid {
static origin = {x: 0, y: 0};
calculateDistanceFromOrigin(point: {x: number; y: number;}) {
var xDist = (point.x - Grid.origin.x);
var yDist = (point.y - Grid.origin.y);
return Math.sqrt(xDist * xDist + yDist * yDist) /
this.scale;
}
constructor (public scale: number) { }
}
var Grid = (function () {
function Grid(scale) {
this.scale = scale;
}
Grid.prototype.calculateDistanceFromOrigin = function (point) {
var xDist = (point.x - Grid.origin.x);
var yDist = (point.y - Grid.origin.y);
return Math.sqrt(xDist * xDist + yDist * yDist) /
this.scale;
};
Grid.origin = { x: 0, y: 0 };
return Grid;
})();
Classes(10)
Advanced Techniques - Constructor functions
class Greeter {
greeting: string;
constructor(message: string) {
this.greeting = message;
}
greet() {
return "Hello, " + this.greeting;
}
}
var greeter: Greeter;
greeter = new Greeter("world");
alert(greeter.greet());
var Greeter = (function () {
function Greeter(message) {
this.greeting = message;
}
Greeter.prototype.greet = function () {
return "Hello, " + this.greeting;
};
return Greeter;
})();
var greeter;
greeter = new Greeter("world");
alert(greeter.greet());
Classes(11)
Advanced Techniques - Constructor functions
class Greeter {
static standardGreeting = "Hello,
there";
greeting: string;
greet() {
if (this.greeting) {
return "Hello, " +
this.greeting;
}
else {
return Greeter.standardGreeting;
}
}
}
var greeter2:Greeter = new
greeterMaker();
alert(greeter2.greet());
var greeterMaker: typeof Greeter = Greeter;
greeterMaker.standardGreeting = "Hey there!";
var greeter1: Greeter;
greeter1 = new Greeter();
alert(greeter1.greet());
Classes(12)
Advanced Techniques - Using a class as an interface
class Point {
x: number;
y: number;
}
interface Point3d extends Point {
z: number;
}
var point3d: Point3d = {x: 1, y: 2, z: 3};
End

More Related Content

What's hot

Swift 함수 커링 사용하기
Swift 함수 커링 사용하기Swift 함수 커링 사용하기
Swift 함수 커링 사용하기진성 오
 
C# Starter L04-Collections
C# Starter L04-CollectionsC# Starter L04-Collections
C# Starter L04-CollectionsMohammad Shaker
 
First-Class Patterns
First-Class PatternsFirst-Class Patterns
First-Class PatternsJohn De Goes
 
44CON 2013 - The Forger's Art: Exploiting XML Digital Signature Implementatio...
44CON 2013 - The Forger's Art: Exploiting XML Digital Signature Implementatio...44CON 2013 - The Forger's Art: Exploiting XML Digital Signature Implementatio...
44CON 2013 - The Forger's Art: Exploiting XML Digital Signature Implementatio...44CON
 
Model-Driven Software Development - Static Analysis & Error Checking
Model-Driven Software Development - Static Analysis & Error CheckingModel-Driven Software Development - Static Analysis & Error Checking
Model-Driven Software Development - Static Analysis & Error CheckingEelco Visser
 
JavaScript Arrays
JavaScript Arrays JavaScript Arrays
JavaScript Arrays Reem Alattas
 
The java language cheat sheet
The java language cheat sheetThe java language cheat sheet
The java language cheat sheetanand_study
 
C# v8 new features - raimundas banevicius
C# v8 new features - raimundas baneviciusC# v8 new features - raimundas banevicius
C# v8 new features - raimundas baneviciusRaimundas Banevičius
 
Tuga IT 2017 - What's new in C# 7
Tuga IT 2017 - What's new in C# 7Tuga IT 2017 - What's new in C# 7
Tuga IT 2017 - What's new in C# 7Paulo Morgado
 
Scala Functional Patterns
Scala Functional PatternsScala Functional Patterns
Scala Functional Patternsleague
 

What's hot (17)

Swift 함수 커링 사용하기
Swift 함수 커링 사용하기Swift 함수 커링 사용하기
Swift 함수 커링 사용하기
 
C# Starter L04-Collections
C# Starter L04-CollectionsC# Starter L04-Collections
C# Starter L04-Collections
 
PDBC
PDBCPDBC
PDBC
 
OOP v3
OOP v3OOP v3
OOP v3
 
First-Class Patterns
First-Class PatternsFirst-Class Patterns
First-Class Patterns
 
44CON 2013 - The Forger's Art: Exploiting XML Digital Signature Implementatio...
44CON 2013 - The Forger's Art: Exploiting XML Digital Signature Implementatio...44CON 2013 - The Forger's Art: Exploiting XML Digital Signature Implementatio...
44CON 2013 - The Forger's Art: Exploiting XML Digital Signature Implementatio...
 
Why Haskell
Why HaskellWhy Haskell
Why Haskell
 
Model-Driven Software Development - Static Analysis & Error Checking
Model-Driven Software Development - Static Analysis & Error CheckingModel-Driven Software Development - Static Analysis & Error Checking
Model-Driven Software Development - Static Analysis & Error Checking
 
For Beginners - C#
For Beginners - C#For Beginners - C#
For Beginners - C#
 
JavaScript Arrays
JavaScript Arrays JavaScript Arrays
JavaScript Arrays
 
Scala best practices
Scala best practicesScala best practices
Scala best practices
 
Fp201 unit4
Fp201 unit4Fp201 unit4
Fp201 unit4
 
Joy of scala
Joy of scalaJoy of scala
Joy of scala
 
The java language cheat sheet
The java language cheat sheetThe java language cheat sheet
The java language cheat sheet
 
C# v8 new features - raimundas banevicius
C# v8 new features - raimundas baneviciusC# v8 new features - raimundas banevicius
C# v8 new features - raimundas banevicius
 
Tuga IT 2017 - What's new in C# 7
Tuga IT 2017 - What's new in C# 7Tuga IT 2017 - What's new in C# 7
Tuga IT 2017 - What's new in C# 7
 
Scala Functional Patterns
Scala Functional PatternsScala Functional Patterns
Scala Functional Patterns
 

Viewers also liked

Type script by Howard
Type script by HowardType script by Howard
Type script by HowardLearningTech
 
Byte array to hex string transformer
Byte array to hex string transformerByte array to hex string transformer
Byte array to hex string transformerRahul Kumar
 
5 2. string processing
5 2. string processing5 2. string processing
5 2. string processing웅식 전
 
Strings Arrays
Strings ArraysStrings Arrays
Strings Arraysphanleson
 
Design, Simulation and Verification of Generalized Photovoltaic cells Model U...
Design, Simulation and Verification of Generalized Photovoltaic cells Model U...Design, Simulation and Verification of Generalized Photovoltaic cells Model U...
Design, Simulation and Verification of Generalized Photovoltaic cells Model U...IDES Editor
 
Ukraine english translation 678
Ukraine english translation 678Ukraine english translation 678
Ukraine english translation 678app_don
 
Как все построено в Dropbox
Как все построено в DropboxКак все построено в Dropbox
Как все построено в DropboxNatalia Sakhnova
 
Ukraine exports 569
Ukraine exports 569Ukraine exports 569
Ukraine exports 569app_don
 
Data pemakaian kabel , dll.
Data pemakaian kabel , dll.Data pemakaian kabel , dll.
Data pemakaian kabel , dll.Reza Hardy
 
Ukraine export restrictions 656
Ukraine export restrictions 656Ukraine export restrictions 656
Ukraine export restrictions 656app_don
 
G T V L D Familiedagvoorstelling
G T    V L D FamiliedagvoorstellingG T    V L D Familiedagvoorstelling
G T V L D FamiliedagvoorstellingGT Tervuren
 
Ukraine english translation 680
Ukraine english translation 680Ukraine english translation 680
Ukraine english translation 680app_don
 
Direcciones web y videos
Direcciones web y videosDirecciones web y videos
Direcciones web y videosVirginiaFrias
 

Viewers also liked (20)

Type script by Howard
Type script by HowardType script by Howard
Type script by Howard
 
Java SE 8
Java SE 8Java SE 8
Java SE 8
 
Byte array to hex string transformer
Byte array to hex string transformerByte array to hex string transformer
Byte array to hex string transformer
 
array
array array
array
 
5 2. string processing
5 2. string processing5 2. string processing
5 2. string processing
 
Strings Arrays
Strings ArraysStrings Arrays
Strings Arrays
 
Design, Simulation and Verification of Generalized Photovoltaic cells Model U...
Design, Simulation and Verification of Generalized Photovoltaic cells Model U...Design, Simulation and Verification of Generalized Photovoltaic cells Model U...
Design, Simulation and Verification of Generalized Photovoltaic cells Model U...
 
Ukraine english translation 678
Ukraine english translation 678Ukraine english translation 678
Ukraine english translation 678
 
Presentation_NEW.PPTX
Presentation_NEW.PPTXPresentation_NEW.PPTX
Presentation_NEW.PPTX
 
Как все построено в Dropbox
Как все построено в DropboxКак все построено в Dropbox
Как все построено в Dropbox
 
Ukraine exports 569
Ukraine exports 569Ukraine exports 569
Ukraine exports 569
 
Data pemakaian kabel , dll.
Data pemakaian kabel , dll.Data pemakaian kabel , dll.
Data pemakaian kabel , dll.
 
Img0109 a
Img0109 aImg0109 a
Img0109 a
 
Ukraine export restrictions 656
Ukraine export restrictions 656Ukraine export restrictions 656
Ukraine export restrictions 656
 
G T V L D Familiedagvoorstelling
G T    V L D FamiliedagvoorstellingG T    V L D Familiedagvoorstelling
G T V L D Familiedagvoorstelling
 
Ukraine english translation 680
Ukraine english translation 680Ukraine english translation 680
Ukraine english translation 680
 
Pr 070410
Pr 070410Pr 070410
Pr 070410
 
El sistema solar
El sistema solar El sistema solar
El sistema solar
 
Presentation_NEW.PPTX
Presentation_NEW.PPTXPresentation_NEW.PPTX
Presentation_NEW.PPTX
 
Direcciones web y videos
Direcciones web y videosDirecciones web y videos
Direcciones web y videos
 

Similar to TypeScript by Howard

Typescript - A developer friendly javascript
Typescript - A developer friendly javascriptTypescript - A developer friendly javascript
Typescript - A developer friendly javascriptpradiphudekar
 
[2019-07] GraphQL in depth (serverside)
[2019-07] GraphQL in depth (serverside)[2019-07] GraphQL in depth (serverside)
[2019-07] GraphQL in depth (serverside)croquiscom
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript IntroductionHans Höchtl
 
TypeScript Presentation - Jason Haffey
TypeScript Presentation - Jason HaffeyTypeScript Presentation - Jason Haffey
TypeScript Presentation - Jason HaffeyRalph Johnson
 
Best of build 2021 - C# 10 & .NET 6
Best of build 2021 -  C# 10 & .NET 6Best of build 2021 -  C# 10 & .NET 6
Best of build 2021 - C# 10 & .NET 6Moaid Hathot
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript IntroductionDmitry Sheiko
 
Csharp4 arrays and_tuples
Csharp4 arrays and_tuplesCsharp4 arrays and_tuples
Csharp4 arrays and_tuplesAbed Bukhari
 
TypeScript - All you ever wanted to know - Tech Talk by Epic Labs
TypeScript - All you ever wanted to know - Tech Talk by Epic LabsTypeScript - All you ever wanted to know - Tech Talk by Epic Labs
TypeScript - All you ever wanted to know - Tech Talk by Epic LabsAlfonso Peletier
 
C# 6.0 - April 2014 preview
C# 6.0 - April 2014 previewC# 6.0 - April 2014 preview
C# 6.0 - April 2014 previewPaulo Morgado
 
CodeCamp Iasi 10 march 2012 - Practical Groovy
CodeCamp Iasi 10 march 2012 - Practical GroovyCodeCamp Iasi 10 march 2012 - Practical Groovy
CodeCamp Iasi 10 march 2012 - Practical GroovyCodecamp Romania
 
Python programming workshop
Python programming workshopPython programming workshop
Python programming workshopBAINIDA
 
LECTURE 2 MORE TYPES, METHODS, CONDITIONALS.pdf
LECTURE 2 MORE TYPES, METHODS, CONDITIONALS.pdfLECTURE 2 MORE TYPES, METHODS, CONDITIONALS.pdf
LECTURE 2 MORE TYPES, METHODS, CONDITIONALS.pdfShashikantSathe3
 

Similar to TypeScript by Howard (20)

Typescript - A developer friendly javascript
Typescript - A developer friendly javascriptTypescript - A developer friendly javascript
Typescript - A developer friendly javascript
 
Einführung in TypeScript
Einführung in TypeScriptEinführung in TypeScript
Einführung in TypeScript
 
Dotnet 18
Dotnet 18Dotnet 18
Dotnet 18
 
[2019-07] GraphQL in depth (serverside)
[2019-07] GraphQL in depth (serverside)[2019-07] GraphQL in depth (serverside)
[2019-07] GraphQL in depth (serverside)
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript Introduction
 
TypeScript Presentation - Jason Haffey
TypeScript Presentation - Jason HaffeyTypeScript Presentation - Jason Haffey
TypeScript Presentation - Jason Haffey
 
Best of build 2021 - C# 10 & .NET 6
Best of build 2021 -  C# 10 & .NET 6Best of build 2021 -  C# 10 & .NET 6
Best of build 2021 - C# 10 & .NET 6
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript Introduction
 
130717666736980000
130717666736980000130717666736980000
130717666736980000
 
Introduction to Groovy
Introduction to GroovyIntroduction to Groovy
Introduction to Groovy
 
Typescript
TypescriptTypescript
Typescript
 
Csharp4 arrays and_tuples
Csharp4 arrays and_tuplesCsharp4 arrays and_tuples
Csharp4 arrays and_tuples
 
TypeScript - All you ever wanted to know - Tech Talk by Epic Labs
TypeScript - All you ever wanted to know - Tech Talk by Epic LabsTypeScript - All you ever wanted to know - Tech Talk by Epic Labs
TypeScript - All you ever wanted to know - Tech Talk by Epic Labs
 
Scala introduction
Scala introductionScala introduction
Scala introduction
 
TechTalk - Dotnet
TechTalk - DotnetTechTalk - Dotnet
TechTalk - Dotnet
 
recap-js-and-ts.pdf
recap-js-and-ts.pdfrecap-js-and-ts.pdf
recap-js-and-ts.pdf
 
C# 6.0 - April 2014 preview
C# 6.0 - April 2014 previewC# 6.0 - April 2014 preview
C# 6.0 - April 2014 preview
 
CodeCamp Iasi 10 march 2012 - Practical Groovy
CodeCamp Iasi 10 march 2012 - Practical GroovyCodeCamp Iasi 10 march 2012 - Practical Groovy
CodeCamp Iasi 10 march 2012 - Practical Groovy
 
Python programming workshop
Python programming workshopPython programming workshop
Python programming workshop
 
LECTURE 2 MORE TYPES, METHODS, CONDITIONALS.pdf
LECTURE 2 MORE TYPES, METHODS, CONDITIONALS.pdfLECTURE 2 MORE TYPES, METHODS, CONDITIONALS.pdf
LECTURE 2 MORE TYPES, METHODS, CONDITIONALS.pdf
 

More from LearningTech

More from LearningTech (20)

vim
vimvim
vim
 
PostCss
PostCssPostCss
PostCss
 
ReactJs
ReactJsReactJs
ReactJs
 
Docker
DockerDocker
Docker
 
Semantic ui
Semantic uiSemantic ui
Semantic ui
 
node.js errors
node.js errorsnode.js errors
node.js errors
 
Process control nodejs
Process control nodejsProcess control nodejs
Process control nodejs
 
Expression tree
Expression treeExpression tree
Expression tree
 
SQL 效能調校
SQL 效能調校SQL 效能調校
SQL 效能調校
 
flexbox report
flexbox reportflexbox report
flexbox report
 
Vic weekly learning_20160504
Vic weekly learning_20160504Vic weekly learning_20160504
Vic weekly learning_20160504
 
Reflection &amp; activator
Reflection &amp; activatorReflection &amp; activator
Reflection &amp; activator
 
Peggy markdown
Peggy markdownPeggy markdown
Peggy markdown
 
Node child process
Node child processNode child process
Node child process
 
20160415ken.lee
20160415ken.lee20160415ken.lee
20160415ken.lee
 
Peggy elasticsearch應用
Peggy elasticsearch應用Peggy elasticsearch應用
Peggy elasticsearch應用
 
Expression tree
Expression treeExpression tree
Expression tree
 
Vic weekly learning_20160325
Vic weekly learning_20160325Vic weekly learning_20160325
Vic weekly learning_20160325
 
D3js learning tips
D3js learning tipsD3js learning tips
D3js learning tips
 
git command
git commandgit command
git command
 

Recently uploaded

Science&tech:THE INFORMATION AGE STS.pdf
Science&tech:THE INFORMATION AGE STS.pdfScience&tech:THE INFORMATION AGE STS.pdf
Science&tech:THE INFORMATION AGE STS.pdfjimielynbastida
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024The Digital Insurer
 
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024BookNet Canada
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxMaking_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxnull - The Open Security Community
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphNeo4j
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptxLBM Solutions
 
APIForce Zurich 5 April Automation LPDG
APIForce Zurich 5 April  Automation LPDGAPIForce Zurich 5 April  Automation LPDG
APIForce Zurich 5 April Automation LPDGMarianaLemus7
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
costume and set research powerpoint presentation
costume and set research powerpoint presentationcostume and set research powerpoint presentation
costume and set research powerpoint presentationphoebematthew05
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 

Recently uploaded (20)

Science&tech:THE INFORMATION AGE STS.pdf
Science&tech:THE INFORMATION AGE STS.pdfScience&tech:THE INFORMATION AGE STS.pdf
Science&tech:THE INFORMATION AGE STS.pdf
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptxVulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
 
The transition to renewables in India.pdf
The transition to renewables in India.pdfThe transition to renewables in India.pdf
The transition to renewables in India.pdf
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024
 
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxMaking_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping Elbows
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptx
 
APIForce Zurich 5 April Automation LPDG
APIForce Zurich 5 April  Automation LPDGAPIForce Zurich 5 April  Automation LPDG
APIForce Zurich 5 April Automation LPDG
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
costume and set research powerpoint presentation
costume and set research powerpoint presentationcostume and set research powerpoint presentation
costume and set research powerpoint presentation
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 

TypeScript by Howard

  • 3. Basic Types(1) TypeScript JavaScript Boolean var isDone: boolean = false; var isDone = false; Number var height: number = 6; var height = 6; String var name: string = "bob"; var name = "bob"; name = 'smith'; name = 'smith'; Array type of the elements followed by '[]' var list:number[] = [1, 2, 3]; var list = [1, 2, 3]; Array<elemType> var list:Array<number> = [1, 2, 3]; *JS With Type Annotation
  • 4. Basic Types(2) Enum 1 enum Color {Red, Green, Blue}; var c: Color = Color.Green; Enum 2 enum Color {Red = 1, Green, Blue}; var c: Color = Color.Green; Enum 3 enum Color {Red = 1, Green = 2, Blue = 4}; var c: Color = Color.Green; from a numeric value to the name of that value enum Color {Red = 1, Green, Blue}; var colorName: string = Color[2];
  • 5. Basic Types(3) Enum var Color; enum Color {Red, Green, Blue}; (function (Color) { Color[Color[“Red”] = 0] = “Red”; Color[Color[“Green”] = 1] = “Green”; Color[Color[“Blue”] = 2] = “Blue”; })(Color || (Color = {}));1. Color[Color[“Red”] = 0] = “Red”; Color[“Red”] = 0; Color[0] = “Red”; 2. immediately executing function (function (Color) {...})(); var a = function(Color){...}; a(Color || (Color = {}));3. var Color = {}; (function (Color) {...})(Color);
  • 6. Basic Types(4) Any Allow you to gradually opt-in and opt-out of type-checking during compilation. var notSure: any = 4; notSure = "maybe a string instead"; notSure = false; // okay, definitely a boolean var list:any[] = [1, true, "free"]; list[1] = 100; Void function warnUser(): void { alert("This is my warning message"); }
  • 7. Interfaces(1) One of TypeScript's core principles is that type-checking focuses on the 'shape' that values have. This is sometimes called "duck typing" or "structural subtyping". Start With... using an interface function printLabel(labelledObj: {label: string}) { console.log(labelledObj.label); } var myObj = {size: 10, label: "Size 10 Object"}; printLabel(myObj); interface LabelledValue { label: string; } function printLabel(labelledObj: LabelledValue) { console.log(labelledObj.label); } (JS) function printLabel(labelledObj) { console.log(labelledObj.label); }
  • 8. Interfaces(2) Optional Properties function createSquare(config: SquareConfig): {color: string; area: number} { var newSquare = {color: "white", area: 100}; if (config.color) { newSquare.color = config.color; } if (config.width) { newSquare.area = config.width * config.width; } return newSquare; } var mySquare = createSquare({color: "black"}); interface SquareConfig { color?: string; width?: number; }
  • 9. Interfaces(3) Optional Properties(JS) function createSquare(config: SquareConfig): {color: string; area: number} { var newSquare = {color: "white", area: 100}; if (config.color) { newSquare.color = config.color; } if (config.width) { newSquare.area = config.width * config.width; } return newSquare; } var mySquare = createSquare({color: "black"}); interface SquareConfig { color?: string; width?: number; }
  • 10. Interfaces(3) Function Types var mySearch: SearchFunc; mySearch = function(source: string, subString: string) { var result = source.search(subString); if (result == -1) { return false; } else { return true; } } //mySearch = function(src: string, sub: string) { // var result = src.search(sub); interface SearchFunc { (source: string, subString: string): boolean; }
  • 11. Interfaces(4) Array Types Dictionary interface StringArray { [index: number]: string; } var myArray: StringArray; myArray = ["Bob", "Fred"]; interface Dictionary { [index: string]: string; length: number; // error, the type of 'length' is not a subtype of the indexer owner: string; } var dic: Dictionary; dic.length: return a number => dic[“length”]
  • 12. Interfaces(5) Class Types - Implementing an interface interface ClockInterface { currentTime: Date; } class Clock implements ClockInterface { currentTime: Date; constructor(h: number, m: number) { } } var Clock = (function() { function Clock(h, m) { } return Clock; })(); var a = function Clock(h, m) { }; var b = function() { return a; }; var Clock = b();
  • 13. Interfaces(6) Class Types - Implementing an interface interface ClockInterface { currentTime: Date; setTime(d: Date); } class Clock implements ClockInterface { currentTime: Date; setTime(d: Date) { this.currentTime = d; } constructor(h: number, m: number) { } } var Clock = (function() { function Clock(h, m) { } Clock.prototype.setTime = function(d) { this.currentTime = d; }; return Clock; })();
  • 14. Interfaces(7) Class Types - Difference between static/instance side of class You may notice that if you create an interface with a construct signature and try to create a class that implements this interface you get an error: This is because when a class implements an interface, only the instance side of the class is checked. Since the constructor sits in the static side, it is not included in this check. Instead, you would need to work with the 'static' side of the class directly. interface ClockInterface { new (hour: number, minute: number); } //Class ‘Clock’ incorrectly implements interface ‘ClockInterface’ class Clock implements ClockInterface { currentTime: Date; constructor(h: number, m: number) { } } interface ClockStatic { new (hour: number, minute: number); } class Clock { currentTime: Date; constructor(h: number, m: number) { } } var cs: ClockStatic = Clock; var newClock = new cs(7, 30);
  • 15. Interfaces(8) Extending Interfaces interface Shape { color: string; } interface Square extends Shape { sideLength: number; } var square = <Square>{}; square.color = "blue"; square.sideLength = 10; interface Shape { color: string; } interface PenStroke { penWidth: number; } interface Square extends Shape, PenStroke { sideLength: number; } var square = <Square>{}; square.color = "blue"; square.sideLength = 10; square.penWidth = 5.0;var square = {}; square.color = "blue"; square.sideLength = 10; square.penWidth = 5.0;
  • 16. Interfaces(8) Class Types - Hybrid Types interface Counter { (start: number): string; interval: number; reset(): void; } var c: Counter; //undefined c(10); c.reset(); c.interval = 5.0;
  • 17. Classes(1) Classes class Greeter { greeting: string; constructor(message: string) { this.greeting = message; } greet() { return "Hello, " + this.greeting; } } var greeter = new Greeter("world"); var Greeter = (function() { function Greeter(message) { this.greeting = message; } Greeter.prototype.greet = function() { return "Hello, " + this.greeting; } } var greeter = new Greeter("world");
  • 18. Classes(2) Inheritance var sam = new Snake("Sammy"); var tom: Animal = new Horse("Tommy"); sam.move(); tom.move(34); class Animal { name:string; constructor(theName: string) { this.name = theName; } move(meters: number = 0) { alert(this.name + " moved " + meters + "m."); } } class Snake extends Animal { constructor(name: string) { super(name); } move(meters = 5) { alert("Slithering..."); super.move(meters); } } class Horse extends Animal { constructor(name: string) { super(name); } move(meters = 45) { alert("Galloping..."); super.move(meters); } }
  • 19. Classes(3) Inheritance(JS) var Animal = (function() { function Animal(theName) { this.name = theName; } Amimal.prototype.move = function(meters) { if (meters === void 0) { meters = 0; } alert(this.name + " moved " + meters + "m."); }; return Animal; })(); var Snake = (function(_supper) { __extends(Snake, _super); function Snake(name) { _super.call(this, name); } Amimal.prototype.move = function(meters) { if (meters === void 0) { meters = 5; } alert("Slithering...”); _super.prototype.move.call(this, meters); }; return Snake; })(Animal);
  • 20. Classes(4) Private/Public modifiers - Public by default class Animal { private name:string; constructor(theName: string) { this.name = theName; } move(meters: number) { alert(this.name + " moved " + meters + "m."); } }
  • 21. Classes(5) Private/Public modifiers - Understanding private For two types to be considered compatible, if one of them has a private member, then the other must have a private member that originated in the same declaration. class Animal { private name:string; constructor(theName: string) { this.name = theName; } } class Rhino extends Animal { constructor() { super("Rhino"); } } class Employee { private name:string; constructor(theName: string) { this.name = theName; } } var animal = new Animal("Goat"); var rhino = new Rhino(); var employee = new Employee("Bob"); animal = rhino; animal = employee; //error: Animal and Employee are not compatible
  • 22. Classes(6) Private/Public modifiers - Parameter properties Using 'private' in this way creates and initializes a private member, and similarly for 'public'. class Animal { constructor(private name: string) { } move(meters: number) { alert(this.name + " moved " + meters + "m."); } }
  • 23. Classes(7) Without Accessors(get/set) class Employee { fullName: string; } var employee = new Employee(); employee.fullName = "Bob Smith"; if (employee.fullName) { alert(employee.fullName); } var Employee = (function () { function Employee() { } return Employee; })(); var employee = new Employee(); employee.fullName = "Bob Smith"; if (employee.fullName) { alert(employee.fullName); }
  • 24. Classes(8) With Accessors(get/set) var passcode = "passcode"; class Employee { private _fullName: string; get fullName(): string { return this._fullName; } set fullName(newName: string) { if (passcode && passcode == "passcode") { this._fullName = newName; } else { alert("Error!"); } } } var employee = new Employee(); employee.fullName = "Bob Smith"; if (employee.fullName) { alert(employee.fullName); } var passcode = "passcode"; var Employee = (function () { function Employee() { } Object.defineProperty(Employee.prototype, "fullName", { get: function () { return this._fullName; }, set: function (newName) { if (passcode && passcode == "passcode") { this._fullName = newName; } else { alert("Error!"); } }, enumerable: true, configurable: true }); return Employee; })();
  • 25. Classes(9) Static Properties class Grid { static origin = {x: 0, y: 0}; calculateDistanceFromOrigin(point: {x: number; y: number;}) { var xDist = (point.x - Grid.origin.x); var yDist = (point.y - Grid.origin.y); return Math.sqrt(xDist * xDist + yDist * yDist) / this.scale; } constructor (public scale: number) { } } var Grid = (function () { function Grid(scale) { this.scale = scale; } Grid.prototype.calculateDistanceFromOrigin = function (point) { var xDist = (point.x - Grid.origin.x); var yDist = (point.y - Grid.origin.y); return Math.sqrt(xDist * xDist + yDist * yDist) / this.scale; }; Grid.origin = { x: 0, y: 0 }; return Grid; })();
  • 26. Classes(10) Advanced Techniques - Constructor functions class Greeter { greeting: string; constructor(message: string) { this.greeting = message; } greet() { return "Hello, " + this.greeting; } } var greeter: Greeter; greeter = new Greeter("world"); alert(greeter.greet()); var Greeter = (function () { function Greeter(message) { this.greeting = message; } Greeter.prototype.greet = function () { return "Hello, " + this.greeting; }; return Greeter; })(); var greeter; greeter = new Greeter("world"); alert(greeter.greet());
  • 27. Classes(11) Advanced Techniques - Constructor functions class Greeter { static standardGreeting = "Hello, there"; greeting: string; greet() { if (this.greeting) { return "Hello, " + this.greeting; } else { return Greeter.standardGreeting; } } } var greeter2:Greeter = new greeterMaker(); alert(greeter2.greet()); var greeterMaker: typeof Greeter = Greeter; greeterMaker.standardGreeting = "Hey there!"; var greeter1: Greeter; greeter1 = new Greeter(); alert(greeter1.greet());
  • 28. Classes(12) Advanced Techniques - Using a class as an interface class Point { x: number; y: number; } interface Point3d extends Point { z: number; } var point3d: Point3d = {x: 1, y: 2, z: 3};
  • 29. End

Editor's Notes

  1. 首先是型別, TS的基礎型別大致上都與JS一樣, 比較特別的是TS提供Enum讓大家使用
  2. 在TS中宣告變數或function時, 是使用: type, 來表示return type, 但更有感覺的說法是, 限制return type, 若對照一下編譯後的JS會發現, 加上去的: type, 並不會影響編譯後的結果, 這裡就能看出TS的一個特色, TS其實是JS With Type Annotation <Number>在TS中, 所有Number都是浮點數 <String>和JS一樣, 除了雙引號, 也能用單引號包字串 <Array>要宣告陣列時, :後面的型別能用兩種方式寫,
  3. 在C#都很常用Enum, 因為能用容易看懂的文字集合來對應原本的數值集合, 因此TS提供這個型別 如同一般Enum, 如果不給數值, 就是從0開始, 其中一個給1, 之後就是2, 3, 4, ... , 或是全都直接給數值 除了能從Enum的項目得到對應的數值, 也能從數值得到對應的Enum項目
  4. 接下來看TS如何在JS實作出Enum的效果, 左側有個Color的Enum, 右側是編譯後的JS 可以分成三個部分看, 第一個是先只看底線的部分, 底線部分的第一行其實是做這兩件事, 我為Color加了一個屬性Red, 而屬性值是”0”, 然後也加了一個屬性0, 屬性值是”Red” 第二個再把底線想像成..., 這個稱為Immediately Executing Function, 若還是看不懂, 可以拆成兩核, 宣告一個a函式, 然後再執行它 第三個是立即執行函式所傳入的參數 Color || (Color = {}), 斜線部分, 其實它就真的只是把Color指定為一個物件而已, 等同於這樣的寫法 所以你若要用JS做一個Enum, 先var個Color為一個物件, 再為Color每個項目設定兩種屬性, Color[“Red”] = 0 和 Color[0]= “Red”
  5. <Any>寫程式時, 可能會有需要描述清楚那些不確定的變數型別之情況, 或是要宣告一個沒特定型別的陣列之情況 <Void>就是不回傳值的型別, 也可以看成是any的相反型別
  6. 在介紹Interface前, 先要知道TS的一個核心價值, 型別檢查機制是注重在變數該有的輪廓, 有時也稱為duck typing或structural subtyping 鴨子型別有引用一句詩, 當看到一隻鳥走起來像鴨子、游泳起來像鴨子、叫起來也像鴨子,那麼這隻鳥就可以被稱為鴨子 這句話表示可以觀察未知事物的外在特徵,以推斷該事物的本質, 在這裡就是指觀察一個物件類別, 可以用這個物件的屬性, 來判斷是否就是我要的類別物件 Interface就是運用這個方法來限制傳入的物件, 在TS中, interface是一個命名型別的角色, 可以用基本型別或函式等的屬性組成一個型別, 但它的功用其實是限制, 以這兩個範例的編譯後JS來看, 在JS中, 呼叫函式帶入的參數用甚麼型別都可以, 而TS中, 有了Interface就會讓TS型別檢查機制找到這個錯誤, 要求你改 <StartWith>型別檢查到你的物件有label這個字串屬性, 滿足return型別所需要屬性的條件, 就算物件內還有其它屬性也沒關係 <using an interface>改以宣告interface寫, 函式的參數要滿足此interface所需要屬性的條件, 注意到我們不需要很明顯地說這裡傳入的參數物件要實作interface等等, 這類在其他語言常見的作法, 因為這純粹只是要給TS的型別檢查機制看的annotation
  7. interface下的屬性不一定全部都需要與傳入參數的屬性match, 只要在屬性名稱後加?, 它就代表是選擇性的屬性, 有也好, 沒有也罷 <Option Properties>在這個範例中, 傳入參數需要合乎這個interface, 但是不一定要有這些選擇性的屬性, 然後函式中先宣告好有給定預設值屬性的物件, 再根據傳入參數有的屬性做覆蓋更新, 最後回傳這個物件 與上個例子正好相反, 上個例子是物件有比interface還多的屬性, 這個則是interface有比物件還多的屬性
  8. interface的能力是能先描述初一個給在JS中物件的範圍輪廓, 除了能以物件的屬性表示, 也能以函式型別表示 若要以函式型別表示, 需要給interface一個呼叫的簽名, 就只要給宣告函式的參數列與return 型別 <Function Types>一但定義好, 就能以之前介紹的用法來使用, 函式型別這種作法, 參數名稱不需要與interface一致 <Comment>函式參數只會根據位置檢查型別, 另外return型別也會檢查
  9. 與函式型別類似, 我們也能以陣列型別表示 <Array types>陣列有一個index的型別, 是指物件索引的型別, 還有一個對應的return型別, 也就是能以索引得到值的型別 index的型別有支援兩種: string and number. <Dictionary>index的型別為string, return型別也為string, 若我還要一個屬性叫length放這個字典裡的數量時, 會出錯 因為字典的寫法恰好就跟屬性的寫法一樣, 所以不能說字典項目要return string, 字典的屬性要return number 無論index型別是string或number, 都會強制所有屬性都要與return型別一致
  10. 最常用interface的語言像是C#和JAVA, 用很明白的方法限制類別(:interface), 在TS也可以達成 能夠以implements來表示類別實作了介面 interface只會表示類別公開的部分, 而不是公開私有都會寫 <Class Types>這樣能禁止你用interface找出類別裡的私有部分
  11. 也可以實作有Methods的Interface
  12. 當在處理類別和介面時, 要記住一件事, 類別有兩個型別, 靜態部分與物件部分 你會發現假如你建了一個有建構子簽名的介面, 想要建立一個實作這介面的類別時會出錯, 這是因為當類別實作介面, 只有類別物件這邊有做型別檢查, 因為建構子是屬於靜態那邊, 所以應該要直接與類別做處理 Instead, you would need to work with the 'static' side of the class directly.
  13. 就像是類別一樣, 介面也能繼承 <left>它將介面的成員複製到另一個上, 讓你有更高的自由度, 能將個別的介面屬性組合 <right>一個介面能繼承多個介面, 建出所有介面的組合
  14. 之前提到, 介面也能表示多種型別的屬性
  15. 傳統JS要寫個類似class的型別都是用function和prototype-based達成 從ECMAScript 6開始, the next version of JavaScript, JavaScript programmers will be able to build their applications using this object-oriented class-based approach. In TypeScript, we allow developers to use these techniques now, and compile them down to JavaScript that works across all major browsers and platforms, without having to wait for the next version of JavaScript. This class has three members, a property called 'greeting', a constructor, and a method 'greet'. You'll notice that in the class when we refer to one of the members of the class we prepend 'this.'. This denotes that it's a member access. In the last line we construct an instance of the Greeter class using 'new'. This calls into the constructor we defined earlier, creating a new object with the Greeter shape, and running the constructor to initialize it.
  16. In TypeScript, we can use common object-oriented patterns. Of course, one of the most fundamental patterns in class-based programming is being able to extend existing classes to create new ones using inheritance. This example covers quite a bit of the inheritance features in TypeScript that are common to other languages. Here we see using the 'extends' keywords to create a subclass. You can see this where 'Horse' and 'Snake' subclass the base class 'Animal' and gain access to its features. The example also shows off being able to override methods in the base class with methods that are specialized for the subclass. Here both 'Snake' and 'Horse' create a 'move' method that overrides the 'move' from 'Animal', giving it functionality specific to each class.
  17. You may have noticed in the above examples we haven't had to use the word 'public' to make any of the members of the class visible. Languages like C# require that each member be explicitly labelled 'public' to be visible. In TypeScript, each member is public by default. You may still mark members a private, so you control what is publicly visible outside of your class.
  18. TypeScript is a structural type system. When we compare two different types, regardless of where they came from, if the types of each member are compatible, then we say the types themselves are compatible. When comparing types that have 'private' members, we treat these differently. For two types to be considered compatible, if one of them has a private member, then the other must have a private member that originated in the same declaration. In this example, we have an 'Animal' and a 'Rhino', with 'Rhino' being a subclass of 'Animal'. We also have a new class 'Employee' that looks identical to 'Animal' in terms of shape. We create some instances of these classes and then try to assign them to each other to see what will happen. Because 'Animal' and 'Rhino' share the private side of their shape from the same declaration of 'private name: string' in 'Animal', they are compatible. However, this is not the case for 'Employee'. When we try to assign from an 'Employee' to 'Animal' we get an error that these types are not compatible. Even though 'Employee' also has a private member called 'name', it is not the same one as the one created in 'Animal'.
  19. The keywords 'public' and 'private' also give you a shorthand for creating and initializing members of your class, by creating parameter properties. The properties let you can create and initialize a member in one step. Here's a further revision of the previous example. Notice how we drop 'theName' altogether and just use the shortened 'private name: string' parameter on the constructor to create and initialize the 'name' member.
  20. TypeScript supports getters/setters as a way of intercepting accesses to a member of an object. This gives you a way of having finer-grained control over how a member is accessed on each object. While allowing people to randomly set fullName directly is pretty handy, this might get us in trouble if we people can change names on a whim.
  21. In this version, we check to make sure the user has a secret passcode available before we allow them to modify the employee. We do this by replacing the direct access to fullName with a 'set' that will check the passcode. We add a corresponding 'get' to allow the previous example to continue to work seamlessly. To prove to ourselves that our accessor is now checking the passcode, we can modify the passcode and see that when it doesn't match we instead get the alert box warning us we don't have access to update the employee.
  22. Up to this point, we've only talked about the instance members of the class, those that show up on the object when its instantiated. We can also create static members of a class, those that are visible on the class itself rather than on the instances. In this example, we use 'static' on the origin, as it's a general value for all grids. Each instance accesses this value through prepending the name of the class. Similarly to prepending 'this.' in front of instance accesses, here we prepend 'Grid.' in front of static accesses.
  23. 當你在TS宣告一個類別, 其實同一時間你也宣告了很多東西, 第一個就是此類別的物件型別 在這個範例中, 第一行var greeter: Greeter, 是用Greeter當作此類別的物件型別, 除此之外, TS做了一個函式, 每當new出一個類別的物件時執行, 稱之為constructor function 在這範例中, constructor function 會assign到var Greeter, 當呼叫new就會執行這個函式, 並得到此類別的物件 這個constructor function會有此類別的所有靜態成員
  24. In this example, 'greeter1' works similarly to before. We instantiate the 'Greeter' class, and use this object. This we have seen before. Next, we then use the class directly. Here we create a new variable called 'greeterMaker'. This variable will hold the class itself, or said another way its constructor function. Here we use 'typeof Greeter', that is "give me the type of the Greeter class itself" rather than the instance type. Or, more precisely, "give me the type of the symbol called Greeter", which is the type of the constructor function. This type will contain all of the static members of Greeter along with the constructor that creates instances of the Greeter class. We show this by using 'new' on 'greeterMaker', creating new instances of 'Greeter' and invoking them as before.
  25. As we said in the previous section, a class declaration creates two things: a type representing instances of the class and a constructor function. Because classes create types, you can use them in the same places you would be able to use interfaces.