The document discusses TypeScript modules. It begins by showing how to organize validators into a single file module. It then demonstrates splitting the module across multiple files by creating LettersOnlyValidator.ts and ZipCodeValidator.ts files that both reference a Validation.ts file and export classes that implement the module's interface. This allows validators to be modularized while splitting code across separate files.
A tour of Python: slides from presentation given in 2012.
[Some slides are not properly rendered in SlideShare: the original is still available at http://www.aleksa.org/2015/04/python-presentation_7.html.]
From java to kotlin beyond alt+shift+cmd+k - Droidcon italyFabio Collini
Kotlin is a first-class language for Android development since Google I/O 2017. And it’s here to stay!
Thanks to Android Studio it’s really easy to introduce Kotlin in an existing project, the configuration is trivial and then we can convert Java classes to Kotlin using a Alt+Shift+Cmd+K. But the new syntax is the just beginning, using Kotlin we can improve our code making it more readable and simpler to write.
In this talk we’ll see how to use some Kotlin features (for example data classes, collections, coroutines and delegates) to simplify Android development comparing the code with the equivalent “modern” Java code. It’s not fair to compare Kotlin code with plain Java 6 code so the Java examples will use lambdas and some external libraries like RxJava and AutoValue.
Function Programming in Scala.
A lot of my examples here comes from the book
Functional programming in Scala By Paul Chiusano and Rúnar Bjarnason, It is a good book, buy it.
A short talk on what makes Functional Programming - and especially Haskell - different.
We'll take a quick overview of Haskell's features and coding style, and then work through a short but complete example of using it for a Real World problem.
http://lanyrd.com/2011/geekup-liverpool-may/sdykh/
A tour of Python: slides from presentation given in 2012.
[Some slides are not properly rendered in SlideShare: the original is still available at http://www.aleksa.org/2015/04/python-presentation_7.html.]
From java to kotlin beyond alt+shift+cmd+k - Droidcon italyFabio Collini
Kotlin is a first-class language for Android development since Google I/O 2017. And it’s here to stay!
Thanks to Android Studio it’s really easy to introduce Kotlin in an existing project, the configuration is trivial and then we can convert Java classes to Kotlin using a Alt+Shift+Cmd+K. But the new syntax is the just beginning, using Kotlin we can improve our code making it more readable and simpler to write.
In this talk we’ll see how to use some Kotlin features (for example data classes, collections, coroutines and delegates) to simplify Android development comparing the code with the equivalent “modern” Java code. It’s not fair to compare Kotlin code with plain Java 6 code so the Java examples will use lambdas and some external libraries like RxJava and AutoValue.
Function Programming in Scala.
A lot of my examples here comes from the book
Functional programming in Scala By Paul Chiusano and Rúnar Bjarnason, It is a good book, buy it.
A short talk on what makes Functional Programming - and especially Haskell - different.
We'll take a quick overview of Haskell's features and coding style, and then work through a short but complete example of using it for a Real World problem.
http://lanyrd.com/2011/geekup-liverpool-may/sdykh/
Some languages, like SML, Haskell, and Scala, have built-in support for pattern matching, which is a generic way of branching based on the structure of data.
While not without its drawbacks, pattern matching can help eliminate a lot of boilerplate, and it's often cited as a reason why functional programming languages are so concise.
In this talk, John A. De Goes talks about the differences between built-in patterns, and so-called first-class patterns (which are "do-it-yourself" patterns implemented using other language features).
Unlike built-in patterns, first-class patterns aren't magical, so you can store them in variables and combine them in lots of interesting ways that aren't always possible with built-in patterns. In addition, almost every programming language can support first-class patterns (albeit with differing levels of effort and type-safety).
During the talk, you'll watch as a mini-pattern matching library is developed, and have the opportunity to follow along and build your own pattern matching library in the language of your choice.
Monads, also known as Kleisli triples in Category Theory, are an (endo-)functor together with two natural transformations, which are surprisingly useful in pure languages like Haskell, but this talk will NOT reference monads. Ever. (Well, at least not in this talk.)
Instead what I intend to impress upon an audience of newcomers to Haskell is the wide array of freely available libraries most of which are liberally licensed open source software, intuitive package management, practical build tools, reasonable documentation (when you know how to read it and where to find it), interactive shell (or REPL), mature compiler, stable runtime, testing tools that will blow your mind away, and a small but collaborative and knowledgeable community of developers. Oh, and some special features of Haskell - the language - too!
"The joy of Scala" - Maxim Novak / Wix
Around eight years ago I started my journey as a developer. Since then, I've played around with many languages and thought that C# offers the best developer productivity. After joining Wix two years ago, I was exposed to the amazing world of Scala and Functional Programming and never looked back.
In Scala the code is much more concise, less ceremonious, immutable by default, combines functional with object oriented, seamlessly interoperates with Java, and many software engineering patterns are already baked into the language. Most importantly - Scala is FUN! By the end of the session you too will, hopefully, convert to Scala and never look back.
Recording of the lecture (Hebrew) - https://youtu.be/TcnYTwff2xU
44CON 2013 - The Forger's Art: Exploiting XML Digital Signature Implementatio...44CON
Many security critical systems rely on the correct implementation of the XML Digital Signature standard for the purposes of verification and identity management. Technologies such as SAML and Web Service Security use the standard, and its sibling XML Encryption, to manage the security of these technologies. Being a standard there is, unsurprisingly, no canonical implementation for any platform or language, with so many different developments there are likely to be differences in how the standard is interpreted.
This presentation is about research done against the main open and closed source implementations of XML Digital Signatures, how they can be exploited to gain remote code execution, signature verification bypass or denial of service. It will show some of the more nasty vulnerabilities found during the research including a novel attack against the built-in Java and .NET libraries which allow for trivial signature spoofing exposing any user of those implementations into accepting an invalid signature which is independent of their usage.
Some languages, like SML, Haskell, and Scala, have built-in support for pattern matching, which is a generic way of branching based on the structure of data.
While not without its drawbacks, pattern matching can help eliminate a lot of boilerplate, and it's often cited as a reason why functional programming languages are so concise.
In this talk, John A. De Goes talks about the differences between built-in patterns, and so-called first-class patterns (which are "do-it-yourself" patterns implemented using other language features).
Unlike built-in patterns, first-class patterns aren't magical, so you can store them in variables and combine them in lots of interesting ways that aren't always possible with built-in patterns. In addition, almost every programming language can support first-class patterns (albeit with differing levels of effort and type-safety).
During the talk, you'll watch as a mini-pattern matching library is developed, and have the opportunity to follow along and build your own pattern matching library in the language of your choice.
Monads, also known as Kleisli triples in Category Theory, are an (endo-)functor together with two natural transformations, which are surprisingly useful in pure languages like Haskell, but this talk will NOT reference monads. Ever. (Well, at least not in this talk.)
Instead what I intend to impress upon an audience of newcomers to Haskell is the wide array of freely available libraries most of which are liberally licensed open source software, intuitive package management, practical build tools, reasonable documentation (when you know how to read it and where to find it), interactive shell (or REPL), mature compiler, stable runtime, testing tools that will blow your mind away, and a small but collaborative and knowledgeable community of developers. Oh, and some special features of Haskell - the language - too!
"The joy of Scala" - Maxim Novak / Wix
Around eight years ago I started my journey as a developer. Since then, I've played around with many languages and thought that C# offers the best developer productivity. After joining Wix two years ago, I was exposed to the amazing world of Scala and Functional Programming and never looked back.
In Scala the code is much more concise, less ceremonious, immutable by default, combines functional with object oriented, seamlessly interoperates with Java, and many software engineering patterns are already baked into the language. Most importantly - Scala is FUN! By the end of the session you too will, hopefully, convert to Scala and never look back.
Recording of the lecture (Hebrew) - https://youtu.be/TcnYTwff2xU
44CON 2013 - The Forger's Art: Exploiting XML Digital Signature Implementatio...44CON
Many security critical systems rely on the correct implementation of the XML Digital Signature standard for the purposes of verification and identity management. Technologies such as SAML and Web Service Security use the standard, and its sibling XML Encryption, to manage the security of these technologies. Being a standard there is, unsurprisingly, no canonical implementation for any platform or language, with so many different developments there are likely to be differences in how the standard is interpreted.
This presentation is about research done against the main open and closed source implementations of XML Digital Signatures, how they can be exploited to gain remote code execution, signature verification bypass or denial of service. It will show some of the more nasty vulnerabilities found during the research including a novel attack against the built-in Java and .NET libraries which allow for trivial signature spoofing exposing any user of those implementations into accepting an invalid signature which is independent of their usage.
Not so long ago Microsoft announced a new language trageting on front-end developers. Everybody's reaction was like: Why?!! Is it just Microsoft darting back to Google?!
So, why a new language? JavaScript has its bad parts. Mostly you can avoid them or workaraund. You can emulate class-based OOP style, modules, scoping and even run-time typing. But that is doomed to be clumsy. That's not in the language design. Google has pointed out these flaws, provided a new language and failed. Will the story of TypeScript be any different?
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...informapgpstrackings
Keep tabs on your field staff effortlessly with Informap Technology Centre LLC. Real-time tracking, task assignment, and smart features for efficient management. Request a live demo today!
For more details, visit us : https://informapuae.com/field-staff-tracking/
Understanding Globus Data Transfers with NetSageGlobus
NetSage is an open privacy-aware network measurement, analysis, and visualization service designed to help end-users visualize and reason about large data transfers. NetSage traditionally has used a combination of passive measurements, including SNMP and flow data, as well as active measurements, mainly perfSONAR, to provide longitudinal network performance data visualization. It has been deployed by dozens of networks world wide, and is supported domestically by the Engagement and Performance Operations Center (EPOC), NSF #2328479. We have recently expanded the NetSage data sources to include logs for Globus data transfers, following the same privacy-preserving approach as for Flow data. Using the logs for the Texas Advanced Computing Center (TACC) as an example, this talk will walk through several different example use cases that NetSage can answer, including: Who is using Globus to share data with my institution, and what kind of performance are they able to achieve? How many transfers has Globus supported for us? Which sites are we sharing the most data with, and how is that changing over time? How is my site using Globus to move data internally, and what kind of performance do we see for those transfers? What percentage of data transfers at my institution used Globus, and how did the overall data transfer performance compare to the Globus users?
A Comprehensive Look at Generative AI in Retail App Testing.pdfkalichargn70th171
Traditional software testing methods are being challenged in retail, where customer expectations and technological advancements continually shape the landscape. Enter generative AI—a transformative subset of artificial intelligence technologies poised to revolutionize software testing.
Into the Box Keynote Day 2: Unveiling amazing updates and announcements for modern CFML developers! Get ready for exciting releases and updates on Ortus tools and products. Stay tuned for cutting-edge innovations designed to boost your productivity.
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...Globus
The Earth System Grid Federation (ESGF) is a global network of data servers that archives and distributes the planet’s largest collection of Earth system model output for thousands of climate and environmental scientists worldwide. Many of these petabyte-scale data archives are located in proximity to large high-performance computing (HPC) or cloud computing resources, but the primary workflow for data users consists of transferring data, and applying computations on a different system. As a part of the ESGF 2.0 US project (funded by the United States Department of Energy Office of Science), we developed pre-defined data workflows, which can be run on-demand, capable of applying many data reduction and data analysis to the large ESGF data archives, transferring only the resultant analysis (ex. visualizations, smaller data files). In this talk, we will showcase a few of these workflows, highlighting how Globus Flows can be used for petabyte-scale climate analysis.
Enterprise Resource Planning System includes various modules that reduce any business's workload. Additionally, it organizes the workflows, which drives towards enhancing productivity. Here are a detailed explanation of the ERP modules. Going through the points will help you understand how the software is changing the work dynamics.
To know more details here: https://blogs.nyggs.com/nyggs/enterprise-resource-planning-erp-system-modules/
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERRORTier1 app
Even though at surface level ‘java.lang.OutOfMemoryError’ appears as one single error; underlyingly there are 9 types of OutOfMemoryError. Each type of OutOfMemoryError has different causes, diagnosis approaches and solutions. This session equips you with the knowledge, tools, and techniques needed to troubleshoot and conquer OutOfMemoryError in all its forms, ensuring smoother, more efficient Java applications.
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...Juraj Vysvader
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I didn't get rich from it but it did have 63K downloads (powered possible tens of thousands of websites).
Navigating the Metaverse: A Journey into Virtual Evolution"Donna Lenk
Join us for an exploration of the Metaverse's evolution, where innovation meets imagination. Discover new dimensions of virtual events, engage with thought-provoking discussions, and witness the transformative power of digital realms."
May Marketo Masterclass, London MUG May 22 2024.pdfAdele Miller
Can't make Adobe Summit in Vegas? No sweat because the EMEA Marketo Engage Champions are coming to London to share their Summit sessions, insights and more!
This is a MUG with a twist you don't want to miss.
Listen to the keynote address and hear about the latest developments from Rachana Ananthakrishnan and Ian Foster who review the updates to the Globus Platform and Service, and the relevance of Globus to the scientific community as an automation platform to accelerate scientific discovery.
First Steps with Globus Compute Multi-User EndpointsGlobus
In this presentation we will share our experiences around getting started with the Globus Compute multi-user endpoint. Working with the Pharmacology group at the University of Auckland, we have previously written an application using Globus Compute that can offload computationally expensive steps in the researcher's workflows, which they wish to manage from their familiar Windows environments, onto the NeSI (New Zealand eScience Infrastructure) cluster. Some of the challenges we have encountered were that each researcher had to set up and manage their own single-user globus compute endpoint and that the workloads had varying resource requirements (CPUs, memory and wall time) between different runs. We hope that the multi-user endpoint will help to address these challenges and share an update on our progress here.
Software Engineering, Software Consulting, Tech Lead.
Spring Boot, Spring Cloud, Spring Core, Spring JDBC, Spring Security,
Spring Transaction, Spring MVC,
Log4j, REST/SOAP WEB-SERVICES.
Cyaniclab : Software Development Agency Portfolio.pdfCyanic lab
CyanicLab, an offshore custom software development company based in Sweden,India, Finland, is your go-to partner for startup development and innovative web design solutions. Our expert team specializes in crafting cutting-edge software tailored to meet the unique needs of startups and established enterprises alike. From conceptualization to execution, we offer comprehensive services including web and mobile app development, UI/UX design, and ongoing software maintenance. Ready to elevate your business? Contact CyanicLab today and let us propel your vision to success with our top-notch IT solutions.
Globus Connect Server Deep Dive - GlobusWorld 2024Globus
We explore the Globus Connect Server (GCS) architecture and experiment with advanced configuration options and use cases. This content is targeted at system administrators who are familiar with GCS and currently operate—or are planning to operate—broader deployments at their institution.
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);
}
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);
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;
})();
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};
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
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);
}
});
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;
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();
當在處理類別和介面時, 要記住一件事, 類別有兩個型別, 靜態部分與物件部分
你會發現假如你建了一個有建構子簽名的介面, 想要建立一個實作這介面的類別時會出錯, 這是因為當類別實作介面, 只有類別物件這邊有做型別檢查, 因為建構子是屬於靜態那邊, 所以應該要直接與類別做處理
Instead, you would need to work with the 'static' side of the class directly.
傳統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.
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.
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.
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'.
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.
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.
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.
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.
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.
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.