TypeScript入门-语法篇

来源:互联网 发布:java变量的主要类型 编辑:程序博客网 时间:2024/06/05 03:40

转自 –> TypeScript入门-语法篇

自学笔记, 基于官方教程上的代码, 添加注释.

官方教程:

Handbook


  • 基本类型 Basic Types
  • 接口 Interfaces
    • 第一个接口 Our First Interface
    • 可选属性 Optional Properties
    • 函数类型 Function Types
    • 数组类型 Array Types
    • 类类型 Class Types
    • 继承接口 Extending Interfaces
    • 混合类型 Hybrid Types
  • 类 Classes
    • 类 Classes
    • 继承 Inheritance
    • 公私 修饰器 PrivatePublic modifiers
      • 默认公有 Public by default
      • 理解私有 Understanding private
      • 参数属性 Parameter properties
    • 访问器 Accessors
    • 静态属性 Static Properties
    • Advanced Techniques
  • 模块 Modules
  • 函数 Functions
  • 泛型 Generics
  • 异常 Common Errors
  • Mixins
  • Declaration Merging
  • Type Inference
  • Type Compatibility
  • Writing dts files

基本类型 Basic Types

// 1. Boolean,布尔var isDone: boolean = false;console.log(isDone);// 2. Number,数值var height: number = 6;console.log(height);// 3. String,字符串var name: string = "bob"; // 可以双引号var name1: string = 'tom'; // 也可以单引号console.log(name);console.log(name1);// 4. Array,数组var list:number[] = [1, 2, 3]; // 写法1var list1:Array<number> = [1, 2, 3]; // 写法2console.log(list);console.log(list1);// 5. Enum,枚举enum Color {Red, Green, Blue}var c: Color = Color.Green;console.log(c); // 获取值console.log(Color[c]); // 获取键, stringconsole.log(Color["Green"]); // 获取值// # enum的值默认从0开始递增, 也可以自己指定enum Color1 {Red = 1, Green = 2, Blue = 4}var c1: Color1 = Color1.Green;console.log(c1); // 获取值// 6. Any,任意对象// # 需要小心使用, 会改变数据类型var anylist:any[] = [1, true, "free"];anylist[2] = 100;console.log(anylist);// 7. Void,方法不返回值function warnUser(): void {    console.log("This is my warning message");}warnUser();

接口 Interfaces

第一个接口 Our First Interface

interface LabelledValue {    label: string;}function printLabel(labelledObj: LabelledValue) {    console.log(labelledObj.label);}var myObj = {label: "only label"};var myObj1 = {size: 10, label: "Size 10 Object"};// # 接口是鸭子类型, 只要是有label的对象都可以传进去printLabel(myObj);printLabel(myObj1);

可选属性 Optional Properties

interface SquareConfig {    color?: string; // 用?来表示可选属性    width?: number;}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"});var mySquare1 = createSquare({width: 20});console.log(mySquare);console.log(mySquare1);

函数类型 Function Types

interface SearchFunc {    (source: string, subString: string): boolean; // 表示一个接受2个string参数, 返回bool的函数}var mySearch: SearchFunc;mySearch = function(source: string, subString: string): boolean {    var result = source.search(subString);    if (result == -1) {        return false;    }    else {        return true;    }};var result: boolean = mySearch("test", "te");console.log(result);

数组类型 Array Types

interface StringArray {    [index: number]: string; // 表示string数组}var myArray: StringArray;myArray = ["Bob", "Fred"];console.log(myArray["0"]);console.log(myArray["1"]);

类类型 Class Types

interface ClockStatic {    new (hour: number, minute: number);}// # 这里会报错. 因为只有实例部分才检查, 而构造函数是静态部分//class Clock implements ClockStatic  {//    currentTime: Date;//    constructor(h: number, m: number) { }//}class Clock {    currentTime: Date;    constructor(h: number, m: number) { }}// # 这里需要注意// # 我们直接使用class,这样就会检查签名var cs: ClockStatic = Clock;var newClock: ClockStatic = new cs(7, 30);console.log(newClock);

继承接口 Extending Interfaces

interface Shape {    color: string;}interface PenStroke {    penWidth: number;}interface Square extends Shape, PenStroke { // 使用extends继承接口    sideLength: number;}var square = <Square>{};square.color = "blue";square.sideLength = 10;square.penWidth = 5.0;

混合类型 Hybrid Types

interface Counter {    (start: number): string;    interval: number;    reset(): void;}var c: Counter;c(10); // c可以当函数c.reset(); // c也可以当对象c.interval = 5.0; // c的属性

类 Classes

类 Classes

class Greeter {    greeting: string; // 属性    constructor(message: string) { // 构造函数        this.greeting = message;    }    greet(): string { // 方法        return "Hello, " + this.greeting;    }}var greeter = new Greeter("world");var result = greeter.greet();console.log(result);

继承 Inheritance

class Animal {    name:string;    constructor(theName: string) { this.name = theName; }    move(meters: number = 0) {        console.log(this.name + " moved " + meters + "m.");    }}class Snake extends Animal { // 使用extends关键字来继承    constructor(name: string) { super(name); }    move(meters = 5) {        console.log("Slithering...");        super.move(meters);    }}class Horse extends Animal {    constructor(name: string) { super(name); }    move(meters = 45) {        console.log("Galloping...");        super.move(meters);    }}var sam = new Snake("Sammy the Python");var tom: Animal = new Horse("Tommy the Palomino");sam.move();tom.move(34);

公/私 修饰器 Private/Public modifiers

默认公有 Public by default

class Animal {    private name:string; // 除非指定为private, 否则默认是public    constructor(theName: string) { this.name = theName; }    move(meters: number) {        alert(this.name + " moved " + meters + "m.");    }}

理解私有 Understanding private

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; // # 这里会报错. 虽然Animal和Employee属性名一致, 但是私有属性来源不一致class A {    public name: string;    echo() {}}class B {    public name: string;    echo() {}}var a = new A();var b = new B();a = b; // 公有属性则没有关系

参数属性 Parameter properties

class Animal {    constructor(private name: string) { } // 可以在构造方法用private直接指定属性,省去一步    move(meters: number) {        console.log(this.name + " moved " + meters + "m.");    }}var dog = new Animal("dog");dog.move(3);

访问器 Accessors

var passcode = "secret passcode";class Employee {    private _fullName: string;    get fullName(): string { // 读属性. # 需要编译版本为ECMAScript 5        return this._fullName;    }    set fullName(newName: string) { // 写属性. # 需要编译版本为ECMAScript 5        if (passcode && passcode == "secret passcode") {            this._fullName = newName;        }        else {            console.log("Error: Unauthorized update of employee!");        }    }}var employee = new Employee();employee.fullName = "Bob Smith";if (employee.fullName) {    console.log(employee.fullName);}

静态属性 Static Properties

class Grid {    static origin = {x: 0, y: 0}; // 用static定义静态属性    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 grid1 = new Grid(1.0);  // 1x scalevar grid2 = new Grid(5.0);  // 5x scaleconsole.log(grid1.calculateDistanceFromOrigin({x: 10, y: 10}));console.log(grid2.calculateDistanceFromOrigin({x: 10, y: 10}));

Advanced Techniques

模块 Modules

函数 Functions

泛型 Generics

异常 Common Errors

Mixins

Declaration Merging

Type Inference

Type Compatibility

Writing .d.ts files

0 0
原创粉丝点击