TypeScript 入门手册

252 阅读3分钟

1、TypeScript安装

  • 直接运行:sudo npm install -g typescript
  • 验证:tsc -v 有版本号出来即为运行成功
  • 直接运行:tsc xx.ts

2、TypeScript介绍

  • 是微软开发的一门语言,是JavaScript的超集,遵循ES6语法

3、TypeScript优势

  • 支持ES6规范
  • 强大的IDE支持:类型检查,语法提示,重构
  • Angular2的开发语言

4、在线compiler(编译)

5、字符串新特性

  • 多行字符串
  • 字符串模版
  • 自动拆分字符串
    • 举个例子:
    function test(template: any, name: any, age: any) { 
      console.log(template)
      console.log(name)
      console.log(age)
    }
    
    var myname = `liu jiana`
    var getAge = function () {
      return 18
    }
    
    test`hello, my name is ${myname}, i'm ${getAge()} years old.`
    
    =>运行出来后的结果为
    [LOG]: [ "hello, my name is ", ", i'm ", " years old." ] 
    [LOG]: liu jiana 
    [LOG]: 18 
    // 这个就是自动拆分字符串,将参数拆分成一个字符串数组,然后剩下的参数依次对应起来。
    
  • 参数新特性
    • 参数类型:在参数名称后面使用冒号来指定参数的类型。
      • 参数类型的所有情况:
      var myname: string = 'zhangsan'
      var alias: any = '任意类型'
      var age: number = 12
      var man: boolean = true
      
      function test(name:string): string {
          return name
      }
      test('1')
      class Person {
          name!: string;
          age!: number;
      }
      var person:Person = new Person()
      person.age = 12
      person.name = '23'
      
    • 默认参数:在参数声明后面用等号来指定参数的默认值
      • 如以下例子:
      var myname="liujiana"
      
      function test(a: string, b: string, c: string="jojo") {
          console.log(a)
          console.log(b)
          console.log(c)
      }
      test("xxx", "yyy", "zzz")
      test("xxx", "yyy")
      
    • 可选参数:在方法的参数声明后面用问号来标明此参数为可选参数
      • 如以下例子:
      var myname="liujiana"
      
      function test(a: string, b?: string, c: string="jojo") {
          console.log(a)
          console.log(b)
          console.log(c)
      }
      test("xxx")
      

6、函数新特性

  • 1、Rest and Spread 操作符:用来声明任意数量的方法参数。即...args操作符
    • 如以下例子:传不固定数量的参数
    function func1 (...args: any) {
      args.forEach((arg: any) => {
          console.log(arg)
      })
    }
    func1(1,2,3)
    func1('a', 'b', 'c', 'd')
    
    => 打印结果:
    [LOG]: 1 
    [LOG]: 2 
    [LOG]: 3 
    [LOG]: a 
    [LOG]: b 
    [LOG]: c 
    [LOG]: d 
    
  • 2、generator 函数:控制函数的执行过程,手工暂停和恢复代码执行。通过yield关键字和function后面加*号
    • 如以下例子1:调一次next就打印1,再调一次yield才打印2
    function* doSomething () {
      console.log('1')
      yield
      console.log(2)
    }
    var fun1 = doSomething()
    fun1.next()
    fun1.next()
    
    • 复杂例子2: 通过yield控制代码的暂停和执行
    function* getStockPrice(stock:any) {
      while(true) {
          console.log(stock)
          yield Math.random()*100
      }
    }
    
    var priceGenerator = getStockPrice("IBM")
    var limitPrice = 15
    var price: number = 100
    while(price < limitPrice) {
        price = priceGenerator.next().value
        console.log(`the generator return ${price}`)
    }
    console.log(`buying at ${price}`)
    
  • 3、destructuring 析构表达式:通过表达式将对象或数组拆解成任意数量的变量.(好处:可以从对象或数组中拿特定值时,写更少的代码)
    • 例子1: 拿对象
    function getStock() {
      return {
        code: 'IBM',
        price: {
            price1: 200,
            price2: 400
        },
        aaa: 'xixixi',
        bbb: 'hahaha'
      }
    }
    
    var { code, price: {price2} } = getStock()
    console.log(`code: ${code}`)
    console.log(`price: ${price2}`)
    
    • 例子2: 拿数组
    var array1 = [1, 2, 3, 4]
    var [number1, number2, ...others] = array1
    console.log(`number1: ${number1}`)
    console.log(`number2: ${number2}`)
    console.log(`others: ${others}`)
    

7、表达式和循环

  • 1、箭头表达式:用来声明匿名函数,消除传统匿名函数的this指针问题。
  • 2、forEach(), for in和for of

8、类(class)

  • 类是TypeScript的核心,使用TypeScript开发时,大部分代码都是写在类里面。
  • 1、类的定义
class Person {}
// 这样就定义了一个类
  • 2、类的实例化
class Person {}
var p1 = new Person()
// 这里就实例化出一个p1
  • 3、类的访问控制符
    • pubilc 公共的,类的内部和外部都可以访问到
    • private 私有的,只有在类的内部被访问到
    • protected 受保护的,可以在类的内部和他的子类被访问到,在类的外部不能被访问
  • 4、类的构造函数
class Person {
  constructor(public name:string) {
    
  }
  eat () {
    console.log(this.name)
  }
}

const p1 = new Person('batman')
p1.eat()

const p2 = new Person('superman')
p2.eat()

输出 =>

batman
superman

在实例化的时候会被调用,而且只调用1次,在实例化p1和p2的时候,都只执行了一次constructor,进行赋值,所以就打印出相应的name

  • 5、类的继承:extends和super
// 雇员继承了人,所以继承人所有属性和方法
class Person {
  constructor(public name:string) {}
  eat () {
    console.log(this.name)
  }
}
class Employee extends Person {
  code: string
  constructor(name:string, code: string) {
    super(name)
    console.log('xixi')
    this.code = code
  }
  
  work() {
    super.eat()
    this.doWork()
  }
  private doWork() {
    console.log('im working')
  }
} 
var e1 = new Employee('name', '1')

9、泛型:参数化的类型,一般用来限制集合的内容

var workers: Array<Person> = []
workers[0] = new Person('zhangsan')
workers[1] = new Employee('zhangsan', 2)
workers[2] = 2

10、接口:用来建立某种代码约定,使得其他开发者在调用某个方法或创建新的类时必须遵循接口所定义的代码约定

  • 接口的使用示例1如下:
interface IPerson { // 声明个接口
  name: string,
  age: number
}

class Person {
  constructor (public config: IPerson) { // 声明个类,传入接口对应的属性

  }
}

var p1 = new Person ({ // 声明个实例传入对应的接口属性
  name: '111',
  age: 12
})
  • 接口的使用示例2:implement, 实现
interface Animal {
  eat(): any
}

class Sheep implements Animal { // Sheep这个类实现了Animal这个接口,所以就必须实现里面的所有方法和属性。
  eat () {
    console.log('111')
  }
}

class Tiger implements Animal {
  eat () {
    console.log('im eat meat')
  }
}

11、模块:模块可以帮助开发者将代码分割为可重用的单元。开发者可以自己决定将模块中的哪些资源(类、方法、变量)暴露出去供外部使用。

12、注解:为程序的元素(类、方法、变量)加上更直观明了的说明,这些说明信息与程序的业务逻辑无关,而是供指定的工具或框架使用的。

13、类型定义文件(*.d.ts)