TypeScript入门

TypeScript入门

这是学AngularJS 2 所需要学的知识。

  1. 声明字符串的时候,用[ `` ](键盘上1左边那个键)来括住字符串,可以在字符串换行,TS会转为[ \n ]。

  2. 在[ `` ]中可以写变量和函数的调用。

    1
    console.log(`hello ${var} ${function()}`)
  3. 使用[ `` ]调用函数的时候,可以自动拆分字符串。

    1
    function test(a,b,c){} test`hello ${ee} is ${ff}`
  4. 声明变量后冒号填写变量类型,之后赋值的时候会检查类型。

    1
    var myname: string = 'John'; /* number, boolean */
  1. 变量类型为[ any ]的时候,可以赋所有值。

    1
    var alias: any = 'ii';
  2. 函数的类型可以设置为[ void ]。

    1
    function test(): void{ ... }
  3. 为函数的参数指定默认值。

    1
    function test(a: string = 'jojo'){ ... }
  4. 函数参数中需要使用可选参数的时候,在变量后面加上问号。

    1
    function test(a?: string){ ... }
  5. 函数参数传入任意数量的参数。

    1
    function func1(...args){ ... }
  6. 用关键字[ yield ]可以暂停代码执行,ES6特性,TypeScript暂不支持,用[ next() ]调用。

  7. 通过函数关键字后面加上星号声明generator函数。

    1
    function* getStockPrice(stock) { ... }
  8. 析构表达式可以拆分获取的对象为变量,变量名需要对应,或者取别名。

    1
    2
    3
    4
    5
    function getStock(){
    return {code: "IBM", price:{ price1: 100, price2: 200 };
    }
    var {code: codex, price: {price2}} = getStock();
    // codex = "IBM", price = 200
  9. 用析构表达式拆分数组里面的数据。

    1
    2
    var array1 = [1, 2, 3, 4, 5];
    var [number1, , number3, ...other] = array1; /* 1, 3, [4, 5] */ ]
  10. 箭头表达式,用来声明匿名函数,消除传统匿名函数的this指针问题。

    1
    var sum = {arg1, arg2} => { arg1 + arg2; }
  11. 循环语法[ forEach(), for in, for of ]

    1
    2
    3
    forEach(): 无法在循环中跳出循环,且无法循环属性值。
    [ for(var n in array){ ... } ]: 循环数组的key值,可以用[ break ]跳出。
    [ for(var n of array){ ... } ]: 循环数组的value值,可以用[ break ]跳出。
  12. TypeScript的核心是类,大部分代码都是写在类里面的。

    1
    class Person{ name; eat(){ ... } } var p1 = new Person();
  13. class内的变量有三种访问控制符,默认是[ public ],还有[ private, protected ]。

  14. 在class内写[ constructor(public name:string){ … } ]作为构造函数,只有实例化时才会调用。

  15. 用[ extends ]声明类的继承关系。

    1
    class Employee extends Person { ... }
  16. 用[ super ]调用父类的构造函数,子类另写构造函数的时候必须调用父类的构造函数。

  17. [ interface ]可以作为参数的类型。

    1
    interface IPerson{ ... } class Person{ constructor(public config: IPerson){ ... } }
  18. [ interface ]可以用于class的实现,class必须重写接口中的方法。

    1
    class Person implement IPerson{ ... }
  19. [ export ]表示对外暴露,加在变量或方法或类的声明前面,只有对外暴露才能在其他文件[ import ]。

    1
    export var name = "hoho";
  20. 注解用[ @ ]来表示,在AngularJS 2 中解释为需要引入的文件。

    1
    @Component({selector: 'app-root', templateUrl: './app-com.html', styleUrls: ['./app-s.css'] })
  21. 在TypeScript中使用已有的工具包,其后缀名是.d.ts。

    1
    https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/jquery
文章目录
,