为什么选择
TypeScript 增加了代码的可读性和可维护性
TypeScript文档
TypeScript 编译
tsc
- 编译器会从当前目录开始去查找
tsconfig.json
文件,逐级向上搜索父目录。 - 且使用命令行参数
--project
(或-p
)指定一个包含tsconfig.json
文件的目录。 - 当命令行上指定了输入文件时,
tsconfig.json
文件会被忽略。
TypeScript 配置文件
tsconfig.json
配置可分为两部分
- compilerOptions 规则配置
- files,include, exclude 文件过滤
{
"compilerOptions": {},
"files": [],
"include": [],
"exclude": []
}
需要注意的点
include
可以和file
联用exclude
只对include
有效,对files
无效- 如果
files
和include
都未设置,那么除了exclude
排除的文件,编译器会默认包含路径下的所有TS
文件
compilerOptions
'compilerOptions': {
/* 编译选项 */
'target': 'es5', //指定ECMAScript的目标版本,默认es3
'module': 'commonjs', //使用指定的模块:commonjs、amd、system、umd或es2015
'lib': [], //指定要包含在编译中的库文件
'allowJs': true, //允许编译JavaScript文件
'checkJs': true, //报告JavaScript文件中的错误
'jsx': 'preserve', //指定jsx代码的生成: preserve、react-native或react
'declaration': true, //生成相应的.d.ts文件
'sourceMap': true, //生成相应的.map文件
'outFile': './', //将输入文件合并为一个文件
'outDir': './', //指定输出目录
'rootDir': './', //用来控制输出目录结构--outDir
'removeComments': true, //删除编译后的所有注释
'noEmit': true, //不生成输出文件
'importHelpers': true, //从tslib中导入辅助工具函数
'isolatedModules': true, //将每个文件作为单独的模块、与ts.transpileModule相似
/* 严格的类型检查选项 */
'strict': true, //启用所有严格类型检查选项
'noImplicitany': true, //当在表达式和声明上有隐含的any时报错
'strictNullChecks': true, //启用严格的Null检查
'noImplicitThis': true, //当this表达式的值为any时,生成一个错误
'alwaysStrict': true, //以严格模式检查每个模块,并在所有文件中加入'use strict'
/* 额外的检查 */
'noUnusedLocals': true, //当有未使用的变量时,抛出错误
'noUnusedParameters': true, //当有未使用的参数时,抛出错误
'noImplicitReturns': true, //在并非所有函数的代码都有返回值时,抛出错误
'noFallthroughCasesInSwitch': true, //报告switch语句的fallthrough错误,不允许switch的case语句贯穿
/* 模块解析选项 */
'moduleResolution': 'node', //选中模块的解析策略
'baseUrl': './', //用于解析非相应模块名称基目录
'paths': {}, //模块名到基于baseUrl的路径的映射列表
'rootDirs': [], //根文件夹列表,其组合内容表示项目运行时的结构内容
'typeRoots': [], //包含类型声明的文件列表
'types': [], //需要包含的类型声明文件列表
'allowSyntheticDefaultImports': true, //允许在没有设置默认导出的模块中默认导出
/* Source Map选项 */
'sourceRoot': './', //指定调试器应该找到TypeScript文件,而不是源文件的位置
'mapRoot': './', //指定调试器应该找到映射文件,而不是生成的文件位置
'inlineSourceMap': true, //允许生成单个sourceMaps文件,而不是将sourceMaps生成不同的文件
'inlineSources': true, //将代码与sourceMaps生成到一个文件中,要求同时设置--inlineSourceMap或--sourceMap属性
/* 其他选项 */
'experimentalDecorators': true, //启用装饰器
'emitDecoratorMetadata': true, //为装饰器提供元数据的支持
}
声明文件 xxx.d.ts
用处
- 代码提示
- 开源项目会用到
# 语法
declare var 声明全局变量
declare function 声明全局方法
declare class 声明全局类
declare enum 声明全局枚举类型
declare namespace 声明(含有子属性的)全局对象
interface 和 type 声明全局类型
export 导出变量
export namespace 导出(含有子属性的)对象
export default ES6 默认导出
export = commonjs 导出模块
export as namespace UMD 库声明全局变量
declare global 扩展全局变量
declare module 扩展模块
/// <reference /> 三斜线指令
ts语法
# 基础数据类型
# Boolean、Number、String、null、undefined、Symbol
let a: number = 1;
let b: string = '1';
let c: boolean = false;
# 对象类型
let a: number[] = [1, 1, 2, 3, 5];
let a: Array<number> = [1, 1, 2, 3, 5];// 泛型定义方式
interface NumberArray {
[index: number]: number;
}
let fibonacci: NumberArray = [1, 1, 2, 3, 5];// 接口定义方式
# 伪数组
function a() {
let args: IArguments = arguments;
}
# 函数
function a(x: number, y: number): number {
return x + y;
}
function a(x: number, y: number): void {
}
# 函数表达式
let a = function (x: number, y: number): number {
return x + y;
}
let a: (x: number, y: number) => number = function (x: number, y: number): number {
return x + y;
}
interface AA {
(x?: number): number
}
let a:AA = function(x?: number) {
return 1
}
function a(x: string, y: string = '你好'): string {// 设置默认值 会被默认为可选参数
return x + ' ' + y;
}
function a(x: number, ...items: any[]) {// 剩余参数
}
断言
值 as 类型
<类型>值
interface
# 可选属性
interface Person {
name: string;
age?: number;
}
let tom: Person = {
name: 'Tom'
};
# 任意属性
interface Person {
name: string;
age?: number;
[propName: string]: any;
}
let tom: Person = {
name: 'Tom',
gender: 'male'
};
interface NumberArray {
[index: number]: number;
}
let fibonacci: NumberArray = [1, 1, 2, 3, 5];
type
# 字符串字面量类型
type EventNames = 'click' | 'scroll' | 'mousemove';
function handleEvent(ele: Element, event: EventNames) {
}
元祖
let tom: [string, number] = ['Tom', 25];
泛型
function a(value: any): Array<any> {// 没有约定返回类型
return [value];
}
function a<T>( value: T): Array<T> {// T代指任意类型
return [value];
}
内置扩展类型
- Boolean、Error、Date、RegExp
- Document、HTMLElement、Event、NodeList
- IArguments 伪数组
内置扩展实际定义规则
interface IArguments {
[index: number]: any;
length: number;
callee: Function;
}
let body: HTMLElement = document.body;
let allDiv: NodeList = document.querySelectorAll('div');
document.addEventListener('click', function(e: MouseEvent) {
});