Interface:接口完成

  1. 用来定义对象的类型

    Generics:泛型

    1. 泛指的类型
    2. function join<T>(first:T, second:T) {
    3. return `${first}${second}`
    4. }
    5. join<T>('1', '2')
    6. function joinTwo<T, P>(first:T, second:P) {
    7. return `${first}${second}`
    8. }
    9. joinTwo<number, string>(1, '2')

    Classes:类

Enums:枚举类型

  1. enum Status {
  2. OFFLINE,
  3. ONLINE = 4,
  4. DELETED
  5. }
  6. // 0 4 5
  7. console.log(Status.OFFLINE) // 0
  8. console.log(Status[4]) // ONLINE

联合类型

  1. function fn(string: Dog | Cat)

联合类型类型保护

  1. typeof
  2. in
  3. instanceof // 只能使用在class的情况下使用
  4. 断言:(animal as Dog).wang()

ts-node
build : ‘tsc -w’
start: ‘nodemon node ./build/crowller.js’
concurrently:并行执行
tsc —init:创建tsconfig.json文件

配置文件及TS命令
tsc 命令会根据 tsconfig.json配置把文件下所有的ts文件进行编译为js
tsc demo.ts:只是编译一个文件,不会根据tsconfig.json配置进行
ts-node demo.ts:这个工具会使用tsconfig.json配置进行编译

exclude:排除需要编译的文件
include:包含需要编译的文件

namespace

  1. 类似于模块化的开发方案,避免所有的类成为全局变量
  2. ///<reference path="./components.ts"> 标注引用外部的命名空间
  3. namespace Home {
  4. class Header {
  5. constructor(){
  6. const ele = document.createElement('div')
  7. ele.innerText = 'This is Header'
  8. document.body.appendChild(div)
  9. }
  10. }
  11. export class Page {
  12. constructor(){
  13. new Header()
  14. }
  15. }
  16. }
  17. new Home.page()

函数重载

  1. 函数可以通过传递不同的参数进行重载 ```javascript interface Jqueryinstance { html: (html :string) => Jqueryinstance }

declare function $(params: () => void) : void declare function $(params: string) : { html: (html :string) => {} }

// 使用interface语法实现重载 interface Jquery { (readyFunc:() => void): void; (selector:string): Jqueryinstance; } declare var $: Jquery ```

如何学习TS

  1. 任何变量都声明类型
  2. 不到万不得已不要用any
  3. 给你的对象声明接口