`
sillycat
  • 浏览: 2486933 次
  • 性别: Icon_minigender_1
  • 来自: 成都
社区版块
存档分类
最新评论

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

    博客分类:
  • UI
 
阅读更多
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

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics