TypeScript指南

# TypeScript指南

# Typescript环境配置

### 初始化tsconfig配置
tsc --init

### 基础命令
tsc index.ts

### 编译JS标准版本
tsc index.ts -t es6

### 编译适配库
tsc index.ts --lib es6

### 编译生成声明文件
tsc index.ts -d -t es6
1
2
3
4
5
6
7
8
9
10
11
12
13
14

# tsconfig 配置

开箱即用的 tsconfig 配置

{
  "compilerOptions": {
    "target": "esnext",     /* 指定编译JS标准 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017','ES2018' or 'ESNEXT'. */
    "module": "commonjs",   /* 编译模式,  'none', 'commonjs', 'amd', 'system', 'commonjs', 'es2015', or 'ESNext'. */
    "outDir": "build",      /* 编译输出目录 */
    "declaration": true,    /* 创建声明文件 `.d.ts` */
  },
  "include": [
    "src/**/*"
  ],
  "exclude": [
    "node_modules",
    "**/*.spec.ts",
    "**/*.spec.ts"
  ]
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

declare var document: any;

const isArray = (object: object) => {
  return Object.prototype.toString.call(object).substr(8, 5) === 'Array';
};

const isObject = (object: object) => {
  return Object.prototype.toString.call(object).substr(8, 6) === 'Object';
};

const isString = (object: object) => {
  return Object.prototype.toString.call(object).substr(8, 6) === 'String';
};

const getQueryParam = (qs: string) => {
  qs = qs.split('+').join(' ');
  let params:any = {};
  let tokens;
  let re = /[?&]?([^=]+)=([^&]*)/g;
  while (tokens = re.exec(qs)) {
    params[decodeURIComponent(tokens[1])] = decodeURIComponent(tokens[2]);
  }
  return params;
}

const getQueryParamByName = (url: string, name: string) => {
  if (!url) url = location && location.search
  const match = RegExp('[?&]' + name + '=([^&]*)').exec(url)
  return match && decodeURIComponent(match[1].replace(/\+/g, ' '))
}

const promiseMiddleware = (middlewares: any[], ctx: any) => {
  let promise = Promise.resolve(null);
  let next;

  // 将ctx绑定到每个方法的this以及第一个参数
  middlewares.forEach((fn, i) => {
    middlewares[i] = fn.bind(null, ctx);
  });

  while ((next = middlewares.shift())) {
    promise = promise.then(next);
  }

  return promise.then(() => {
    return ctx;
  });
}

const addStyle =  (styleString: string) => {
  let style = document.createElement('style');
  style.type = 'text/css';
  style.innerHTML = styleString;
  document.getElementsByTagName('head')[0].appendChild(style);
};

const objectMapQuery = (obj: any) => {
  let ret = [];
  for (let key in obj) {
    ret.push(`${key}=${obj[key]}`);
  }

  return ret.join('&');
}


export {
  isArray,
  isObject,
  isString,
  getQueryParam,
  getQueryParamByName,
  promiseMiddleware,
  addStyle,
  objectMapQuery
}

export default {
  isArray,
  isObject,
  isString,
  getQueryParam,
  getQueryParamByName,
  promiseMiddleware,
  addStyle,
  objectMapQuery
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
上次更新: 2022/7/8 下午4:56:35