|
TypeScript was developed by Microsoft superset of JavaScript, TypeScript compatible with JavaScript, JavaScript code can be loaded and run. TypeScript compared with local JavaScript Progress comprising: adding comments to make the compiler support objects and understand the function, the compiler will remove comments without increasing overhead; add a complete class structure, so that it is traditional for the update object language.
TypeScript Microsoft's official website http://www.typescriptlang.org/
TypeScript source http://typescript.codeplex.com
1. Basic Data Types
Boolean
// Boolean
var isDone: boolean = false;
Number
// Number
var width: number = 100;
String
// String
var name: string = "hello";
Array
// Array
var list: number [] = [1, 2, 3];
var list: Array < number> = [1, 2, 3];
Enum
// Enum
enum Color {Red, Green, Blue}
var c: Color = Color.Red;
alert (c); // default index starts at 0, alert (0);
// You can specify index manually
enum Color1 {Red = 1, Green, Blue}
var c1: Color1 = Color1.Green;
alert (c1); // alert (2)
// Find the name according to the subscript
enum Color2 {Red = 1, Green = 2, Blue = 4}
var c2: string = Color2 [4];
alert (c2); // alert (Blue)
Any
// Unsure, exit compile inspection
var notSure: any = 4;
notSure = "maybe a string instead";
notSure = false; // okay, definitely a boolean
// Sure array element type
var anylist: any [] = [1, true, "free"];
anylist [1] = 100;
Void
//blank
function warnUser (): void {
alert (123);
}
2. Class
The basic syntax
class Animal {
animalName: string;
constructor (name: string) {
this.animalName = name;
}
sayHello () {
alert (this.animalName + ": Hello");
}
}
var tom = new Animal ( "Tom");
tom.sayHello (); // alert (Tom: Hello)
inherit
class Animal {
animalName: string;
constructor (name: string) {
this.animalName = name;
}
sayHello () {
alert (this.animalName + ": Hello");
}
}
class Cat extends Animal {
// Rewrite sayHello method
sayHello () {
alert (this.animalName + "(Cat):" + "Hello");
}
}
class Mouse extends Animal {
sayHello () {
alert (this.animalName + "(Mouse):" + "Hello");
}
}
var tom: Animal = new Cat ( "Tom");
tom.sayHello (); // alert (Tom (Cat): Hello)
var jerry: Animal = new Mouse ( "Jerry");
jerry.sayHello (); // alert (Jerry (Mouse): Hello)
Modifiers
When we changed to private animalName
class Animal {
private animalName: string; // default is public
constructor (name: string) {
this.animalName = name;
}
// ...
}
class Cat extends Animal {
// Rewrite sayHello method
sayHello () {
alert (this.animalName + "(Cat):" + "Hello"); // Error compiler does not pass
}
}
get, set accessor
class Animal {
private _animalName: string; // default is public
get animalName (): string {
return this._animalName;
}
set animalName (name: string): string {
this._animalName = name;
}
// ...
}
Static properties
// Static properties
class Table {
static width = 100;
static height = 200;
}
var width = Table.width;
alert (width); // alert (100)
3. Interface
The basic syntax
interface ICar {
color: string;
}
class Bus implements ICar {
color: string;
constructor () {
this.color = "Blue";
}
}
var bus = new Bus ();
alert (bus.color);
Inherited Interface
// Inheritance Interface
interface Shape {
color: string;
}
interface PenStroke {
penWidth: number;
}
interface Square extends Shape, PenStroke {
sideLength: number;
}
Optional attributes
interface ICar {
color: string;
? SafetyDevice: any; // implementation class does not implement
}
function MoveCar (car: ICar) {
if (car.safetyDevice)
{
alert ( "The car is safe");
}
else
{
alert ( "The car is not safe");
}
}
4. The module (Modules)
Role: 1 to prevent namespace conflicts; 2 function modules can be easily divided into different files easier to maintain;.
The basic syntax
module MyDemo {
export interface IDemo {
}
export class Demo implements IDemo {
}
}
Aliases
module Shapes {
export module Polygons {
export class Triangle {}
export class Square {}
}
}
import polygons = Shapes.Polygons;
var sq = new polygons.Square (); // similar to the 'new Shapes.Polygons.Square ()'
5. Function (Function)
The basic syntax
function add (x: number, y: number): number {
return x + y;
}
// Or
var myAdd = function (x: number, y: number): number {
return x + y;
};
Full function type
var myAdd: (x: number, y: number) => number =
function (x: number, y: number): number {
return x + y;
};
To enhance readability, to the parameter x, y has practical significance, can be written
var myAdd: (baseValue: number, increment: number) => number =
function (x: number, y: number): number {
return x + y;
};
The second part number is a return type, if without the return type, use the 'void'
The third part of the type of function parameters, depending on the context type inference can be omitted
var myAdd: (baseValue: number, increment: number) => number =
function (x, y) {
return x + y;
};
Optional parameters
// Optional parameter
function buildName (firstName: string, lastName:? string) {
if (lastName)
return firstName + "" + lastName;
else return firstName;
}
var result1 = buildName ( "Bob");
The default parameters
// Default parameters
function buildNameDefaultValue (firstName: string, lastName = "Smith") {
return firstName + "" + lastName;
}
var result1 = buildNameDefaultValue ( "Bob");
Variable parameter
For example, in C #, method parameters are defined using the param int [], when calling the method, you can pass multiple parameters of type int
In the TypeScript
function buildNameRest (firstName: string, ... restOfName: string []) {
return firstName + "" + restOfName.join ( "");
}
var employeeName = buildNameRest ( "Joseph", "Samuel", "Lucas", "MacKinzie")
Lambads and this keyword
var people = {
name: [ "Joe Smith", "John Doe", "Wang five", "Zhao six"],
getName: function () {
return function () {
var i = Math.floor (Math.random () * 4);
return {
n: this.name [i]
}
}
}
}
var pname = people.getName ();
alert ( "name:" + pname () n.);
Call getName found in this key point is getName, less than the external access attribute name
So we revised as follows:
var people = {
name: [ "Joe Smith", "John Doe", "Wang five", "Zhao six"],
getName: function () {
return () => {
var i = Math.floor (Math.random () * 4);
return {
n: this.name [i]
}
}
}
}
var pname = people.getName ();
alert ( "name:" + pname () n.);
Overloaded
// Overload
function student (name: string): string;
function student (age: number): number;
function student (numberorage: any): any {
if (numberorage && typeof (numberorage) == "string")
alert ( "name");
else
alert ( "Age");
}
student ( "Tom"); // alert ( "name")
student (15); // alert ( "Age")
5. Generics
The basic syntax
Generic type (generic function type)
Generic Interface
Generic class
class GenericNumber < T> {
zeroValue: T;
add: (x: T, y: T) => T;
}
var myGenericNumber = new GenericNumber < number> ();
myGenericNumber.zeroValue = 0;
myGenericNumber.add = function (x, y) {
return x + y;
};
function identity < T> (arg: T): T {
return arg;
}
// Array of generics
function identity < T> (arg: T []): T [] {
console.log (arg.length);
}
function identity < T> (arg: T): T {
return arg;
}
var myIdentity: < T> (arg: T) => T = identity; // T may also be used other letters
// Can also write
// Var myIdentity: {< T> (arg: T): T} = identity;
interface GenericIdentityFn {
< T> (arg: T): T;
}
function identity < T> (arg: T): T {
return arg;
}
var myIdentity: GenericIdentityFn = identity;
Generic constraints
interface Lengthwise {
length: number;
}
function loggingIdentity < T extends Lengthwise> (arg: T): T {
console.log (arg.length);
return arg;
}
loggingIdentity (3); // error
loggingIdentity ({length: 10, value: 3}); // Just type attribute to contain length
Generic class constraint
class Findable < T>
{
// ...
}
function find < T> (n: T, s: Findable < T>) {
// ...
}
6. Merge
Merge Interface
interface Box {
height: number;
width: number;
}
interface Box {
scale: number;
}
var box: Box = {height: 5, width: 6, scale: 10};
Merge Modules
module Animals {
exportclass Zebra {}
}
module Animals {
exportinterface Legged {numberOfLegs: number;}
exportclass Dog {}
}
// Equivalent
module Animals {
exportinterface Legged {numberOfLegs: number;}
exportclass Zebra {}
exportclass Dog {}
}
Merge modules and classes
class Album {
label: Album.AlbumLabel;
}
module Album {
export class AlbumLabel {
}
}
Merge modules and functions
function buildLabel (name: string): string {
return buildLabel.prefix + name + buildLabel.suffix;
}
module buildLabel {
export var suffix = "";
export var prefix = "Hello,";
}
alert (buildLabel ( "Sam Smith"));
Merge module enumeration
enum Color {
red = 1,
green = 2,
blue = 4
}
module Color {
export function mixColor (colorName: string) {
if (colorName == "yellow") {
return Color.red + Color.green;
}
else if (colorName == "white") {
return Color.red + Color.green + Color.blue;
}
else if (colorName == "magenta") {
return Color.red + Color.blue;
}
else if (colorName == "cyan") {
return Color.green + Color.blue;
}
}
}
Can not be combined
Classes and class can not be combined
Interfaces and classes can not be combined
Variables can not be combined with class |
|
|
|