2018 TypeScript Update(2)Introduction Basic Grammar - Classes and Functions

2018 TypeScript Update(2)Introduction Basic Grammar - Classes and Functions

Classes
http://www.typescriptlang.org/docs/handbook/classes.html
Functions and prototype-based inheritance to build reusable components.

The class Greeter has three members: a property called greeting, a constructor, and a method greet.

Inheritance
Dog extends Animal

Public, Private and Protected Modifiers
In typescript, each member is public by default.

Readonly modifier
class Octopus{
readonly name: string;
readonly numberOfLegs: number = 8;
constructor (theName: string) {
this.name = theName;
}
}
let dad = new Octopus(“Man with 8 legs”);
dad.name = “main with suit”; //error, can not do on readonly

Getter and Setter
class Employee {
private _fullName: string;
get fullName(): string {
return this._fullName;
}
set fullName(newName: string){
..snip...
}
}
let employee = new Employee();
employee.fullName = “Carl Luo”;

Static Properties
Abstract Classes
abstract class may have some implementation
abstract class Animal {
abstract makeSound(): void;
move(): void {
console.log(“rock and roll");
}
}

Functions
http://www.typescriptlang.org/docs/handbook/functions.html
//Named function
function add(x, y) {
return x+y;
}

//Anonymous function
let myAdd = function(x, y) { return x + y; };

We can add types to each of the parameters and then to the function itself to add a return type.

Function Type
let myAdd: (x:number, y: number) => number = function(x: number, y: number): number { return x + y; };

Default and Optional Parameter
function buildName(firstName: string, lastName?: string) {}
function buildName(firstName: string, lastName = “Luo”) {}

Rest Parameters
function buildName(firstName: string, …restOfName: string[]) {}

Generics
http://www.typescriptlang.org/docs/handbook/generics.html
Type Variable
function identity<T>(arg: T): T {
return arg;
}

Generic Classes
class GenericNumber<T> {
zeroValue: T;
add: (x: T, y: T) => T;
}

let myGenericNumber = new GenericNumber<number>();
myGenericNumber.zeroValue = 0;
myGenericNumber.add = function(x, y) { return x+y; };

Enums
http://www.typescriptlang.org/docs/handbook/enums.html
enum Direction { Up, Down, Left, Right }

enum Response {
No = 0,
Yes = 1,
}
function respond(recipient: string, message: Response): void {}
respond(“Princess Caroline”, Response.Yes)

Type Inference http://www.typescriptlang.org/docs/handbook/type-inference.html
Type Compatibility http://www.typescriptlang.org/docs/handbook/type-compatibility.html
Symbols http://www.typescriptlang.org/docs/handbook/symbols.html


References:
http://sillycat.iteye.com/blog/2412076
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值