SlideShare a Scribd company logo
1 of 50
TypeScript(1)
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
TypeScript(2)
Modules
internal module
external module
when each is appropriate and how to use
advanced topics of how to use external modules
address some common pitfalls
Modules(1) - First steps
Validators in a single file
var lettersRegexp = /^[A-Za-z]+$/;
var numberRegexp = /^[0-9]+$/;
class LettersOnlyValidator implements StringValidator {
isAcceptable(s: string) {
return lettersRegexp.test(s);
}
}
class ZipCodeValidator implements StringValidator {
isAcceptable(s: string) {
return s.length === 5 && numberRegexp.test(s);
}
}
interface StringValidator {
isAcceptable(s: string): boolean;
}
Modules(2) - First steps
// Some samples to try
var strings = ['Hello', '98052', '101'];
// Validators to use
var validators: { [s: string]: StringValidator; } = {};
validators['ZIP code'] = new ZipCodeValidator();
validators['Letters only'] = new LettersOnlyValidator();
// Show whether each string passed each validator
strings.forEach(s => {
for (var name in validators) {
console.log('"' + s + '" ' + (validators[name].isAcceptable(s) ? ' matches ' : ' does
not match ') + name);
}
});
interface Validator{
[s: string]: StringValidator;
}
var validators: Validator = {};
interface Validator{
sv: StringValidator;
}
var validators: Validator = {};
"Hello" does not match ZIP code
"Hello" matches Letters only
"98052" matches ZIP code
"98052" does not match Letters
only
"101" does not match ZIP code
Modules(3) - Adding Modularity
Modularized Validators
module Validation {
export interface StringValidator {
isAcceptable(s: string): boolean;
}
var lettersRegexp = /^[A-Za-z]+$/;
var numberRegexp = /^[0-9]+$/;
export class LettersOnlyValidator implements StringValidator {
isAcceptable(s: string) {
return lettersRegexp.test(s);
}
}
export class ZipCodeValidator implements StringValidator {
isAcceptable(s: string) {
return s.length === 5 && numberRegexp.test(s);
}
}
Modules(4) - Adding Modularity
// Some samples to try
var strings = ['Hello', '98052', '101'];
// Validators to use
var validators: { [s: string]: Validation.StringValidator; } = {};
validators['ZIP code'] = new Validation.ZipCodeValidator();
validators['Letters only'] = new Validation.LettersOnlyValidator();
// Show whether each string passed each validator
strings.forEach(s => {
for (var name in validators) {
console.log('"' + s + '" ' + (validators[name].isAcceptable(s) ? ' matches ' : ' does
not match ') + name);
}
});
Modules(5) - Splitting Across Files - Multi-file internal modules
LettersOnlyValidator.ts
/// <reference path="Validation.ts" />
module Validation {
var lettersRegexp = /^[A-Za-z]+$/;
export class LettersOnlyValidator implements
StringValidator {
isAcceptable(s: string) {
return lettersRegexp.test(s);
}
}
}
ZipCodeValidator.ts
/// <reference path="Validation.ts" />
module Validation {
var numberRegexp = /^[0-9]+$/;
export class ZipCodeValidator implements StringValidator {
isAcceptable(s: string) {
return s.length === 5 && numberRegexp.test(s);
}
}
}
Validation.ts
module Validation {
export interface StringValidator {
isAcceptable(s: string): boolean;
}
}
Modules(7) - Splitting Across Files - Multi-file internal modules
Test.ts
/// <reference path="Validation.ts" />
/// <reference path="LettersOnlyValidator.ts" />
/// <reference path="ZipCodeValidator.ts" />
// Some samples to try
var strings = ['Hello', '98052', '101'];
// Validators to use
var validators: { [s: string]: Validation.StringValidator; } = {};
validators['ZIP code'] = new Validation.ZipCodeValidator();
validators['Letters only'] = new Validation.LettersOnlyValidator();
// Show whether each string passed each validator
strings.forEach(s => {
for (var name in validators) {
console.log('"' + s + '" ' + (validators[name].isAcceptable(s) ? ' matches ' : ' does
not match ') + name);
}
});
Modules(8) - Splitting Across Files - Multi-file internal modules
concatenated output
tsc --out sample.js Test.ts
tsc --out sample.js Validation.ts LettersOnlyValidator.ts ZipCodeValidator.ts Test.ts
per-file compilation (the default)
MyTestPage.html (excerpt)
<script src="Validation.js" type="text/javascript" />
<script src="LettersOnlyValidator.js" type="text/javascript" />
<script src="ZipCodeValidator.js" type="text/javascript" />
<script src="Test.js" type="text/javascript" />
Modules(9) - Going External
nodejs requirejs
import someMod = require('someModule');
tsc --module commonjs Test.ts
For node.js, use --module commonjs
For require.js, use --module amd.
Modules(10) - Going External
LettersOnlyValidator.ts
import validation = require('./Validation');
var lettersRegexp = /^[A-Za-z]+$/;
export class LettersOnlyValidator implements validation.StringValidator {
isAcceptable(s: string) {
return lettersRegexp.test(s);
}
}
ZipCodeValidator.ts
import validation = require('./Validation');
var numberRegexp = /^[0-9]+$/;
export class ZipCodeValidator implements validation.StringValidator {
isAcceptable(s: string) {
return s.length === 5 && numberRegexp.test(s);
}
}
Validation.ts
export interface StringValidator {
isAcceptable(s: string): boolean;
}
Modules(11) - Going External
Test.ts
import validation = require('./Validation');
import zip = require('./ZipCodeValidator');
import letters = require('./LettersOnlyValidator');
// Some samples to try
var strings = ['Hello', '98052', '101'];
// Validators to use
var validators: { [s: string]: validation.StringValidator; } = {};
validators['ZIP code'] = new zip.ZipCodeValidator();
validators['Letters only'] = new letters.LettersOnlyValidator();
// Show whether each string passed each validator
strings.forEach(s => {
for (var name in validators) {
console.log('"' + s + '" ' + (validators[name].isAcceptable(s) ? ' matches ' : ' does
not match ') + name);
}
});
Modules(12) - Going External - Code Generation for External Modules
SimpleModule.ts
import m = require('mod');
export var t = m.something + 1;
AMD / RequireJS SimpleModule.js:
define(["require", "exports", 'mod'], function(require, exports, m) {
exports.t = m.something + 1;
});
CommonJS / Node SimpleModule.js:
var m = require('mod');
exports.t = m.something + 1;
Modules(13) - Export =
LettersOnlyValidator.ts
import validation = require('./Validation');
var lettersRegexp = /^[A-Za-z]+$/;
class LettersOnlyValidator implements validation.StringValidator {
isAcceptable(s: string) {
return lettersRegexp.test(s);
}
}
export = LettersOnlyValidator;
ZipCodeValidator.ts
import validation = require('./Validation');
var numberRegexp = /^[0-9]+$/;
class ZipCodeValidator implements validation.StringValidator {
isAcceptable(s: string) {
return s.length === 5 && numberRegexp.test(s);
}
}
export = ZipCodeValidator;
Validation.ts
export interface StringValidator {
isAcceptable(s: string): boolean;
}
Modules(14) - Export =
Test.ts
import validation = require('./Validation');
import zipValidator = require('./ZipCodeValidator');
import lettersValidator = require('./LettersOnlyValidator');
// Some samples to try
var strings = ['Hello', '98052', '101'];
// Validators to use
var validators: { [s: string]: validation.StringValidator; } = {};
validators['ZIP code'] = new zipValidator();
validators['Letters only'] = new lettersValidator();
// Show whether each string passed each validator
strings.forEach(s => {
for (var name in validators) {
console.log('"' + s + '" ' + (validators[name].isAcceptable(s) ? ' matches ' : ' does
not match ') + name);
}
});
Modules(15) - Alias
Basic Aliasing
module Shapes {
export module Polygons {
export class Triangle { }
export class Square { }
}
}
import polygons = Shapes.Polygons;
var sq = new polygons.Square(); // Same as 'new Shapes.Polygons.Square()'
Modules(16) - Optional Module Loading and Other Advanced Loading
Scenarios
Dynamic Module Loading in node.js
declare var require;
import Zip = require('./ZipCodeValidator');
if (needZipValidation) {
var x: typeof Zip = require('./ZipCodeValidator');
if (x.isAcceptable('.....')) { /* ... */ }
}
Sample: Dynamic Module Loading in require.js
declare var require;
import Zip = require('./ZipCodeValidator');
if (needZipValidation) {
require(['./ZipCodeValidator'], (x: typeof Zip) => {
if (x.isAcceptable('...')) { /* ... */ }
});
}
Modules(17) - Working with Other JavaScript Libraries - Ambient Internal
Modules
D3.d.ts (simplified excerpt)
declare module D3 {
export interface Selectors {
select: {
(selector: string): Selection;
(element: EventTarget): Selection;
};
}
export interface Event {
x: number;
y: number;
}
export interface Base extends Selectors {
event: Event;
}
}
declare var d3: D3.Base;
Modules(18) - Working with Other JavaScript Libraries - Ambient External
Modules
node.d.ts (simplified excerpt)
declare module "url" {
export interface Url {
protocol?: string;
hostname?: string;
pathname?: string;
}
export function parse(urlStr: string, parseQueryString?, slashesDenoteHost?): Url;
}
declare module "path" {
export function normalize(p: string): string;
export function join(...paths: any[]): string;
export var sep: string;
} ///<reference path="node.d.ts"/>
import url = require("url");
var myUrl = url.parse("http://www.typescriptlang.org");
Modules(19) - Pitfalls of Modules - /// <reference> to an external module
myModules.d.ts
// In a .d.ts file or .ts file that is not an external module:
declare module "SomeModule" {
export function fn(): string;
}
myOtherModule.ts
/// <reference path="myModules.d.ts" />
import m = require("SomeModule");
Modules(20) - Pitfalls of Modules - Needless Namespacing
shapes.ts
export module Shapes {
export class Triangle { /* ... */ }
export class Square { /* ... */ }
}
shapeConsumer.ts
import shapes = require('./shapes');
var t = new shapes.Shapes.Triangle(); // shapes.Shapes?
Revised Example:
shapes.ts
export class Triangle { /* ... */ }
export class Square { /* ... */ }
shapeConsumer.ts
import shapes = require('./shapes');
var t = new shapes.Triangle();

More Related Content

What's hot

C# Starter L04-Collections
C# Starter L04-CollectionsC# Starter L04-Collections
C# Starter L04-CollectionsMohammad Shaker
 
Swift 함수 커링 사용하기
Swift 함수 커링 사용하기Swift 함수 커링 사용하기
Swift 함수 커링 사용하기진성 오
 
First-Class Patterns
First-Class PatternsFirst-Class Patterns
First-Class PatternsJohn De Goes
 
JavaScript Arrays
JavaScript Arrays JavaScript Arrays
JavaScript Arrays Reem Alattas
 
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
 
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
 
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
 
Coding Guidelines - Crafting Clean Code
Coding Guidelines - Crafting Clean CodeCoding Guidelines - Crafting Clean Code
Coding Guidelines - Crafting Clean CodeGanesh Samarthyam
 
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
 

What's hot (17)

C# Starter L04-Collections
C# Starter L04-CollectionsC# Starter L04-Collections
C# Starter L04-Collections
 
Swift 함수 커링 사용하기
Swift 함수 커링 사용하기Swift 함수 커링 사용하기
Swift 함수 커링 사용하기
 
PDBC
PDBCPDBC
PDBC
 
First-Class Patterns
First-Class PatternsFirst-Class Patterns
First-Class Patterns
 
Why Haskell
Why HaskellWhy Haskell
Why Haskell
 
For Beginners - C#
For Beginners - C#For Beginners - C#
For Beginners - C#
 
OOP v3
OOP v3OOP v3
OOP v3
 
Joy of scala
Joy of scalaJoy of scala
Joy of scala
 
JavaScript Arrays
JavaScript Arrays JavaScript Arrays
JavaScript Arrays
 
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
 
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...
 
Scala best practices
Scala best practicesScala best practices
Scala best practices
 
The java language cheat sheet
The java language cheat sheetThe java language cheat sheet
The java language cheat sheet
 
Fp201 unit4
Fp201 unit4Fp201 unit4
Fp201 unit4
 
C# v8 new features - raimundas banevicius
C# v8 new features - raimundas baneviciusC# v8 new features - raimundas banevicius
C# v8 new features - raimundas banevicius
 
Coding Guidelines - Crafting Clean Code
Coding Guidelines - Crafting Clean CodeCoding Guidelines - Crafting Clean Code
Coding Guidelines - Crafting Clean Code
 
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
 

Similar to Type script by Howard

Typescript - A developer friendly javascript
Typescript - A developer friendly javascriptTypescript - A developer friendly javascript
Typescript - A developer friendly javascriptpradiphudekar
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript IntroductionHans Höchtl
 
[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 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
 
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
 
Csharp4 arrays and_tuples
Csharp4 arrays and_tuplesCsharp4 arrays and_tuples
Csharp4 arrays and_tuplesAbed Bukhari
 
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
 
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
 
C# 6.0 - April 2014 preview
C# 6.0 - April 2014 previewC# 6.0 - April 2014 preview
C# 6.0 - April 2014 previewPaulo Morgado
 

Similar to Type script 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
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript Introduction
 
[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 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
 
130717666736980000
130717666736980000130717666736980000
130717666736980000
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript Introduction
 
Introduction to Groovy
Introduction to GroovyIntroduction to Groovy
Introduction to Groovy
 
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
 
Typescript
TypescriptTypescript
Typescript
 
Csharp4 arrays and_tuples
Csharp4 arrays and_tuplesCsharp4 arrays and_tuples
Csharp4 arrays and_tuples
 
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
 
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
 
C# 6.0 - April 2014 preview
C# 6.0 - April 2014 previewC# 6.0 - April 2014 preview
C# 6.0 - April 2014 preview
 
recap-js-and-ts.pdf
recap-js-and-ts.pdfrecap-js-and-ts.pdf
recap-js-and-ts.pdf
 
ddd+scala
ddd+scaladdd+scala
ddd+scala
 

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

Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionSolGuruz
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsAndolasoft Inc
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️Delhi Call girls
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️anilsa9823
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...panagenda
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsJhone kinadey
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AIABDERRAOUF MEHENNI
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...Health
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Steffen Staab
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 

Recently uploaded (20)

Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 

Type script 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
  • 31. Modules internal module external module when each is appropriate and how to use advanced topics of how to use external modules address some common pitfalls
  • 32. Modules(1) - First steps Validators in a single file var lettersRegexp = /^[A-Za-z]+$/; var numberRegexp = /^[0-9]+$/; class LettersOnlyValidator implements StringValidator { isAcceptable(s: string) { return lettersRegexp.test(s); } } class ZipCodeValidator implements StringValidator { isAcceptable(s: string) { return s.length === 5 && numberRegexp.test(s); } } interface StringValidator { isAcceptable(s: string): boolean; }
  • 33. Modules(2) - First steps // Some samples to try var strings = ['Hello', '98052', '101']; // Validators to use var validators: { [s: string]: StringValidator; } = {}; validators['ZIP code'] = new ZipCodeValidator(); validators['Letters only'] = new LettersOnlyValidator(); // Show whether each string passed each validator strings.forEach(s => { for (var name in validators) { console.log('"' + s + '" ' + (validators[name].isAcceptable(s) ? ' matches ' : ' does not match ') + name); } }); interface Validator{ [s: string]: StringValidator; } var validators: Validator = {}; interface Validator{ sv: StringValidator; } var validators: Validator = {}; "Hello" does not match ZIP code "Hello" matches Letters only "98052" matches ZIP code "98052" does not match Letters only "101" does not match ZIP code
  • 34. Modules(3) - Adding Modularity Modularized Validators module Validation { export interface StringValidator { isAcceptable(s: string): boolean; } var lettersRegexp = /^[A-Za-z]+$/; var numberRegexp = /^[0-9]+$/; export class LettersOnlyValidator implements StringValidator { isAcceptable(s: string) { return lettersRegexp.test(s); } } export class ZipCodeValidator implements StringValidator { isAcceptable(s: string) { return s.length === 5 && numberRegexp.test(s); } }
  • 35. Modules(4) - Adding Modularity // Some samples to try var strings = ['Hello', '98052', '101']; // Validators to use var validators: { [s: string]: Validation.StringValidator; } = {}; validators['ZIP code'] = new Validation.ZipCodeValidator(); validators['Letters only'] = new Validation.LettersOnlyValidator(); // Show whether each string passed each validator strings.forEach(s => { for (var name in validators) { console.log('"' + s + '" ' + (validators[name].isAcceptable(s) ? ' matches ' : ' does not match ') + name); } });
  • 36. Modules(5) - Splitting Across Files - Multi-file internal modules LettersOnlyValidator.ts /// <reference path="Validation.ts" /> module Validation { var lettersRegexp = /^[A-Za-z]+$/; export class LettersOnlyValidator implements StringValidator { isAcceptable(s: string) { return lettersRegexp.test(s); } } } ZipCodeValidator.ts /// <reference path="Validation.ts" /> module Validation { var numberRegexp = /^[0-9]+$/; export class ZipCodeValidator implements StringValidator { isAcceptable(s: string) { return s.length === 5 && numberRegexp.test(s); } } } Validation.ts module Validation { export interface StringValidator { isAcceptable(s: string): boolean; } }
  • 37. Modules(7) - Splitting Across Files - Multi-file internal modules Test.ts /// <reference path="Validation.ts" /> /// <reference path="LettersOnlyValidator.ts" /> /// <reference path="ZipCodeValidator.ts" /> // Some samples to try var strings = ['Hello', '98052', '101']; // Validators to use var validators: { [s: string]: Validation.StringValidator; } = {}; validators['ZIP code'] = new Validation.ZipCodeValidator(); validators['Letters only'] = new Validation.LettersOnlyValidator(); // Show whether each string passed each validator strings.forEach(s => { for (var name in validators) { console.log('"' + s + '" ' + (validators[name].isAcceptable(s) ? ' matches ' : ' does not match ') + name); } });
  • 38. Modules(8) - Splitting Across Files - Multi-file internal modules concatenated output tsc --out sample.js Test.ts tsc --out sample.js Validation.ts LettersOnlyValidator.ts ZipCodeValidator.ts Test.ts per-file compilation (the default) MyTestPage.html (excerpt) <script src="Validation.js" type="text/javascript" /> <script src="LettersOnlyValidator.js" type="text/javascript" /> <script src="ZipCodeValidator.js" type="text/javascript" /> <script src="Test.js" type="text/javascript" />
  • 39. Modules(9) - Going External nodejs requirejs import someMod = require('someModule'); tsc --module commonjs Test.ts For node.js, use --module commonjs For require.js, use --module amd.
  • 40. Modules(10) - Going External LettersOnlyValidator.ts import validation = require('./Validation'); var lettersRegexp = /^[A-Za-z]+$/; export class LettersOnlyValidator implements validation.StringValidator { isAcceptable(s: string) { return lettersRegexp.test(s); } } ZipCodeValidator.ts import validation = require('./Validation'); var numberRegexp = /^[0-9]+$/; export class ZipCodeValidator implements validation.StringValidator { isAcceptable(s: string) { return s.length === 5 && numberRegexp.test(s); } } Validation.ts export interface StringValidator { isAcceptable(s: string): boolean; }
  • 41. Modules(11) - Going External Test.ts import validation = require('./Validation'); import zip = require('./ZipCodeValidator'); import letters = require('./LettersOnlyValidator'); // Some samples to try var strings = ['Hello', '98052', '101']; // Validators to use var validators: { [s: string]: validation.StringValidator; } = {}; validators['ZIP code'] = new zip.ZipCodeValidator(); validators['Letters only'] = new letters.LettersOnlyValidator(); // Show whether each string passed each validator strings.forEach(s => { for (var name in validators) { console.log('"' + s + '" ' + (validators[name].isAcceptable(s) ? ' matches ' : ' does not match ') + name); } });
  • 42. Modules(12) - Going External - Code Generation for External Modules SimpleModule.ts import m = require('mod'); export var t = m.something + 1; AMD / RequireJS SimpleModule.js: define(["require", "exports", 'mod'], function(require, exports, m) { exports.t = m.something + 1; }); CommonJS / Node SimpleModule.js: var m = require('mod'); exports.t = m.something + 1;
  • 43. Modules(13) - Export = LettersOnlyValidator.ts import validation = require('./Validation'); var lettersRegexp = /^[A-Za-z]+$/; class LettersOnlyValidator implements validation.StringValidator { isAcceptable(s: string) { return lettersRegexp.test(s); } } export = LettersOnlyValidator; ZipCodeValidator.ts import validation = require('./Validation'); var numberRegexp = /^[0-9]+$/; class ZipCodeValidator implements validation.StringValidator { isAcceptable(s: string) { return s.length === 5 && numberRegexp.test(s); } } export = ZipCodeValidator; Validation.ts export interface StringValidator { isAcceptable(s: string): boolean; }
  • 44. Modules(14) - Export = Test.ts import validation = require('./Validation'); import zipValidator = require('./ZipCodeValidator'); import lettersValidator = require('./LettersOnlyValidator'); // Some samples to try var strings = ['Hello', '98052', '101']; // Validators to use var validators: { [s: string]: validation.StringValidator; } = {}; validators['ZIP code'] = new zipValidator(); validators['Letters only'] = new lettersValidator(); // Show whether each string passed each validator strings.forEach(s => { for (var name in validators) { console.log('"' + s + '" ' + (validators[name].isAcceptable(s) ? ' matches ' : ' does not match ') + name); } });
  • 45. Modules(15) - Alias Basic Aliasing module Shapes { export module Polygons { export class Triangle { } export class Square { } } } import polygons = Shapes.Polygons; var sq = new polygons.Square(); // Same as 'new Shapes.Polygons.Square()'
  • 46. Modules(16) - Optional Module Loading and Other Advanced Loading Scenarios Dynamic Module Loading in node.js declare var require; import Zip = require('./ZipCodeValidator'); if (needZipValidation) { var x: typeof Zip = require('./ZipCodeValidator'); if (x.isAcceptable('.....')) { /* ... */ } } Sample: Dynamic Module Loading in require.js declare var require; import Zip = require('./ZipCodeValidator'); if (needZipValidation) { require(['./ZipCodeValidator'], (x: typeof Zip) => { if (x.isAcceptable('...')) { /* ... */ } }); }
  • 47. Modules(17) - Working with Other JavaScript Libraries - Ambient Internal Modules D3.d.ts (simplified excerpt) declare module D3 { export interface Selectors { select: { (selector: string): Selection; (element: EventTarget): Selection; }; } export interface Event { x: number; y: number; } export interface Base extends Selectors { event: Event; } } declare var d3: D3.Base;
  • 48. Modules(18) - Working with Other JavaScript Libraries - Ambient External Modules node.d.ts (simplified excerpt) declare module "url" { export interface Url { protocol?: string; hostname?: string; pathname?: string; } export function parse(urlStr: string, parseQueryString?, slashesDenoteHost?): Url; } declare module "path" { export function normalize(p: string): string; export function join(...paths: any[]): string; export var sep: string; } ///<reference path="node.d.ts"/> import url = require("url"); var myUrl = url.parse("http://www.typescriptlang.org");
  • 49. Modules(19) - Pitfalls of Modules - /// <reference> to an external module myModules.d.ts // In a .d.ts file or .ts file that is not an external module: declare module "SomeModule" { export function fn(): string; } myOtherModule.ts /// <reference path="myModules.d.ts" /> import m = require("SomeModule");
  • 50. Modules(20) - Pitfalls of Modules - Needless Namespacing shapes.ts export module Shapes { export class Triangle { /* ... */ } export class Square { /* ... */ } } shapeConsumer.ts import shapes = require('./shapes'); var t = new shapes.Shapes.Triangle(); // shapes.Shapes? Revised Example: shapes.ts export class Triangle { /* ... */ } export class Square { /* ... */ } shapeConsumer.ts import shapes = require('./shapes'); var t = new shapes.Triangle();

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.
  26. 簡易版的字串驗證器, 有字母的, 也有郵遞區號的(5碼數字) 很像是你在 webpage form 裡, 檢查使用者輸入或是檢查外部提供的資料內容 有一個字串驗證的 Interface, 它限制被實作的對象需要有一個 isAcceptable property, 是一個回傳 bool 的method property 兩個 regular patent, 分別 parse 純英文和5碼數字 兩個 class 實作了那個 Interface, 都有 isAcceptable 的 method, 回傳參數是否通過規則
  27. 接著, 寫一些範例 宣告我的 validators, 限制他們的屬性值會是一個 StringValidator Type, 而且這些屬性是以類似 dictionary 的屬性表示 最後將這些測試字串 foreach 跑這兩個 validator
  28. 當我們加進更多 validator, 就需要一些組織架構, 就能繼續 track 自己的型別, 不需要擔心其他物件會有名稱衝突的問題 這個範例中, 我們把所有 validator 相關的 types 都移進 Validation module 裡 因為要讓 module 外面也能夠看得見這些 classes 和 interfaces, 所以開頭都加上 export 相反地, 變數是屬於執行中細節的部分, 所以不需要加
  29. 在測試的地方, 就需要修飾(qualify)這些形態, 改為 module 名稱 Validation 再點形態
  30. 當這個程式越來越龐大時, 就需要將他拆多個檔案, 有易於維護 要讓他們雖然是分開的, 但還是能互相使用, 就如同定義在同個地方一樣 因為在檔案之間有 dependencies (依賴性), 所以加上 reference tag 告訴編譯器檔案之間的依賴關係
  31. 測試的部分都沒改變
  32. 一旦有使用到多個 TS 檔時, 需要確認所有的編譯過的程式碼都有載入 首先, 我們可以用連結式(concatenated)輸出, 用--out flag 編譯所有 TS 成一份JS檔 編譯器會依據 reference tag 自動排序 或者也能個別 TS 編譯 另一種方法, 我們能用單一檔案編譯方法(default 方法)來發送(emit)一份 JS 給每一份檔案 如果產出多個 JS 檔, 就需要用 script tag 載入每一份發送出來的 JS
  33. TS 也有外部 module 的概念, 有兩種 js 會使用到 nodejs requirejs 不用 nodejs 或 requirejs 的應用程式就不需要用外部 modules, 只要用上面所講的內部 module 即可 在外部 modules 中, 檔案之間的關係會由 import 和 export 所指定, 在TS中, 任何檔案最上階層有 import 或 export 就可認定為外部 module 原本的 reference tag 的功能用 import 的句子取代, 指定 modules 之間的依賴關係功能 import 句子有兩部分: 自訂的 module 名稱和 require 裡放 module 路徑 編譯的部分, 我們必須在 command line 就指定一個 module 目標 當編譯完成, 每個外部 module 都會變成個別的 js 檔, 和 reference tag 相似, 編譯器會遵循 import 句子來編譯依賴的檔案
  34. 我們已經把之前的範例轉為使用外部 module, 可以發現不再用 module 關鍵字, 檔案本身組成一個 module 並以檔名來區分 我們在最上階層的宣告是用 export, 指定哪些物件是可以被看見的, 和內部 module 中 export 如何定義公開區域相似
  35. 在編譯期間根據指定的 module, 編譯器會產出適合的 code 給 nodejs(commonjs) 或requirejs(AMD)的module-loading system 簡單的例子說明這些名字如何在 importing 和 exporting 轉變成載入 code 期間使用
  36. 在之前的例子中, 每個 module 只會 export 一個值 eport = 語法能指定一個從 module 輸出的物件, 可以是個 class, interface, module, function 或 enum
  37. 當 import 進來時, 這個被 export 的物件就能直接使用, 而且不用加任何修飾字 簡化了 validator 實作變成從每個 module 輸出單一個物件
  38. 另外一個方法能簡化工作, 用 import q = x.y.z 的方法對常用的物件建比較短的名稱 不要與 import x = require(‘name’) 語法混淆, 那是在載入外部 module 使用 這和用 var 相似, 還能用在 type 和 namespace 上
  39. 在某些情況中, 你可能需要在某些條件下只載入一個 module, 在TS中, 就能下 pattern 來完成它和其他更進一部的載入情境, 直接呼叫 module loader 編譯器會偵測每個 module 是否被使用, 對於只用在部分系統中的 module 而言, 就不需要呼叫 這個功能替除掉不用的 reference 對改善效能很有幫助, 恰好能用在那些 optional 載入的 module 上 pattern 主要核心是這句 import id = require(‘...’) 給我們存取那些從 module 公開出來的型別 module loader 透過 require 動態地被呼叫, module 只在需要時才載入 為了維護型別安全, 我們能用 typeof 關鍵字, 當用在型別位置時, 產生這個值的型別, 這個例子中就是外部 module 的型別
  40. 要說明不是用 TS 寫的函式庫, 需要宣告函式庫公開的 API, 因為大多數 JS 函式庫公開只有少數最上層的物件, 而 module 是一種很好的表示方法 通常情況, 都是定義在 .d.ts 檔 如果你很熟悉 C/C++ 就相當於 .h 檔或 ’extern’ 有名的函式庫D3在全域物件中定義它的功能D3, 因為這個函式庫是要透過 script tag (而不是 module loader)載入, 它是用內部 module 定義 要讓TS編譯器看見這個輪廓, 我們用周圍的內部 module 宣告
  41. 在nodejs中, 大多數的 task 都是載入一或多個 module 來完成 我們可以在自己的 .d.ts 檔先定義每個 module, 會更方便將它們寫成一個更大的 .d.ts 檔 要這樣做, 我們用雙引號包住 module 的名稱, 會在之後 import 能夠用 就可以用 /// <reference> node.d.ts 然後再用 import url = require(“url”) 載入module
  42. 常見的錯誤是用 /// <reference> 語法引用外部 module 檔, 而不是用 import
  43. 若你正在轉換程式, 從內部 module 轉換成外部 module, 很容易會被這種檔卡住 最上層 module, 沒有理由地將 Shapes 包住 Triangle 和 Square, 讓使用你的 module 的使用者非常困擾 在 TS 中外部 module 最關鍵的特色是兩個不同外部 module 決不會提供名稱到相同的 scope 因為使用者能決定要指定甚麼名字, 不需要積極用 namespace 包住