安装 TypeScript
TypeScript 的命令行工具安装方法如下:
npm install -g typescript
以上命令会在全局环境下安装 tsc 命令,安装完成之后,我们就可以在任何地方执行 tsc 命令了。
编译一个 TypeScript 文件很简单:(基本类似于全局安装node, 可以通过node编译并执行 index.js )
tsc hello.ts
TypeScript 中,使用 : 指定变量的类型,: 的前后有没有空格都可以。
上述例子中,我们用 : 指定 person 参数类型为 string。但是编译为 js 之后,并没有什么检查的代码被插入进来。
TypeScript 只会进行静态检查,如果发现有错误,编译的时候就会报错。
**TypeScript 编译的时候即使报错了,还是会生成编译结果,我们仍然可以使用这个编译之后的文件。
如果要在报错的时候终止 js 文件的生成,可以在
tsconfig.json中配置noEmitOnError即可。关于tsconfig.json 请参阅官方手册``[(中文版)](https://zhongsp.gitbooks.io/typescript-handbook/content/doc/handbook/tsconfig.json.html)
Be Careful
- 访问联合类型的属性或方法:当 TypeScript 不确定一个联合类型的变量到底是哪个类型的时候,我们只能访问此联合类型的所有类型里共有的属性或方法.
- 数组的多种声明方式
```
方式1、
let fibonacci: number[] = [1, 1, 2, 3, 5];
方式2、
数组泛型
我们也可以使用数组泛型(Array Generic) Array
来表示数组: let fibonacci: Array = [1, 1, 2, 3, 5]; 方式3、 用接口表示数组;接口也可以用来描述数组: interface NumberArray {
[index: number]: number;
} let fibonacci: NumberArray = [1, 1, 2, 3, 5];
方式4 any 在数组中的应用 let list: any[] = [‘xcatliu’, 25, { website: ‘http://xcatliu.com‘ }];
3. 函数注意点```javascript1. 注意不要混淆了 TypeScript 中的 => 和 ES6 中的 =>。在 TypeScript 的类型定义中,=> 用来表示函数的定义,左边是输入类型,需要用括号括起来,右边是输出类型。在 ES6 中,=> 叫做箭头函数,应用十分广泛,可以参考 ES6 中的箭头函数。2. 可选参数必须接在必需参数后面。换句话说,可选参数后面不允许再出现必需参数了传入参数的声明,可以采用...的方式,则ts的声明可以用 any[]的方式3. 重载允许一个函数接受不同数量或类型的参数时,作出不同的处理。function reverse(x: number): number;function reverse(x: string): string;function reverse(x: number | string): number | string {if (typeof x === 'number') {return Number(x.toString().split('').reverse().join(''));} else if (typeof x === 'string') {return x.split('').reverse().join('');}}上例中,我们重复定义了多次函数 reverse,前几次都是函数定义,最后一次是函数实现。在编辑器的代码提示中,可以正确的看到前两个提示。注意,TypeScript 会优先从最前面的函数定义开始匹配,所以多个函数定义如果有包含关系,需要优先把精确的定义写在前面。
- 类型断言(比较好用,特别在联合类型上)
传入参数something: string | number ;按正常情况下,只能访问string与number共同的方法类型断言可以处理上面的尴尬function getLength(something: string | number): number {if (something.length) {return something.length;} else {return something.toString().length;}}使用类型断言function getLength(something: string | number): number {if ((<string>something).length) {return (<string>something).length;} else {return something.toString().length;}}
- 全局变量的声明文件主要有以下几种语法:
需要注意的是,声明语句中只能定义类型,切勿在声明语句中定义具体的实现declare var 声明全局变量declare let 声明全局变量declare const 声明全局常量, 不可改变在函数类型的声明语句中,函数重载也是支持的declare function 声明全局方法declare class 声明全局类declare enum 声明全局枚举类型declare namespace 声明(含有子属性的)全局对象interface 和 type 声明全局类型
- 字符串字面量(可以用于声明至少是其中一种)
type EventNames = 'click' | 'scroll' | 'mousemove';function handleEvent(ele: Element, event: EventNames) {// do something}handleEvent(document.getElementById('hello'), 'scroll'); // 没问题handleEvent(document.getElementById('world'), 'dbclick'); // 报错,event 不能为 'dbclick'// index.ts(7,47): error TS2345: Argument of type '"dbclick"' is not assignable to parameter of type 'EventNames'.
typescript编译配置 tsconfig.json
作用: 如果一个目录下存在一个tsconfig.json文件,那么它意味着这个目录是TypeScript项目的根目录。 tsconfig.json文件中指定了用来编译这个项目的根文件和编译选项
tsconfig.json的结构
- compilerOptions:可以被忽略,这时编译器会使用默认值。在这里查看完整的编译器选项列表。
- files:指定一个包含相对或绝对路径的列表
- include和exclude属性: 属性指定一个文件glob匹配模式列表,支持global通配符有 :1. 匹配0或者多个字符(不包含目录分隔符);2、 ?匹配一个任意字符(不包括目录分隔符)3、*/递归匹配任意子目录;
- 如果files文件指定的文件,无法用exclude排除
- extends: 是tsconfig.json文件里面的顶级属性
{"compilerOptions": {// 指定生成哪个模块系统代码注意 "ESNext"最新的生成目标列表为 ES proposed features// "ES6"和 "ES2015"可使用在目标输出为 "ES5"或更低的情况下。"module": "esnext",// 指定ECMAScript目标版本"target": "es5",// 允许js,此配置,如果设置全局匹配路径。默认会编译js"allowJs": true,// 编译过程中需要引入的库文件的列表。// lib没有指定默认注入的库的列表。默认注入的库为:// 针对于--target ES5:DOM,ES5,ScriptHost// 针对于--target ES6:DOM,ES6,DOM.Iterable,ScriptHost"lib": ["es2015", "es2017", "dom"],// 在表达式和声明上有隐含的 any类型时报错。"noImplicitAny": true,// 删除所有注释,除了以 /!*开头的版权信息。"removeComments": true,// 保留 const和 enum声明。查看 const enums documentation了解详情。"preserveConstEnums": true,// 生成相应的 .map文件。"sourceMap": false,// 决定如何处理模块。或者是"Node"对于Node.js/io.js,或者是"Classic"(默认)。查看模块解析了解详情。"moduleResolution": "node"}}
代码检测
typescript中使用eslint
- 安装eslint
ESlint默认使用Espree进行语法解析, 则安装ts语法解析器@typescript-eslint/parser
npm install --save-dev typescript @typescript-eslint/parser
接下来需要安装对应的插件 @typescript-eslint/eslint-plugin 它作为 eslint 默认规则的补充,提供了一些额外的适用于 ts 语法的规则。
npm install --save-dev @typescript-eslint/eslint-plugin
TypeScript源代码的解析器转换过程
[@typescript-eslint/parser](https://github.com/typescript-eslint/typescript-eslint/blob/master/packages/parser)实际上,此monorepo中的软件包是在这种情况下我们提供给ESLint的自定义ESLint解析器实现。
发生的流程和转换如下所示:
- ESLint会调用的
parser方法会从您配置ESLint([@typescript-eslint/parser](https://github.com/typescript-eslint/typescript-eslint/blob/master/packages/parser))中指定的 [@typescript-eslint/parser](https://github.com/typescript-eslint/typescript-eslint/blob/master/packages/parser)处理所有ESLint特定的配置,然后调用[@typescript-eslint/typescript-estree](https://github.com/typescript-eslint/typescript-eslint/blob/master/packages/typescript-estree),一个不可知软件包,仅与获取TypeScript源代码并生成适当的AST有关。[@typescript-eslint/typescript-estree](https://github.com/typescript-eslint/typescript-eslint/blob/master/packages/typescript-estree)通过在给定的源代码上调用TypeScript编译器以产生TypeScript AST,然后将该AST转换为ESLint期望的格式,可以工作。
注意:这种AST格式不仅仅用于ESLint,还被更广泛地使用。它甚至有自己的规范,被称为ESTree,这就是为什么我们的软件包被称为typescript-estree。
因为[@typescript-eslint/typescript-estree](https://github.com/typescript-eslint/typescript-eslint/blob/master/packages/typescript-estree)具有非常特定的用途,所以可将其重用于与ESLint具有类似要求的工具。因此,它还可以为功能强大的固执的代码格式化程序Prettier的TypeScript用例提供支持。
官方文档的部分解析:
TypeScript和ESLint具有相似的用途
这意味着在某些情况下,TypeScript确实为我们解决了我们以前依赖ESLint的问题。这两种解决方案可能具有相似的目的,但结果不同,或者在其他方面不兼容。处理此类情况的最佳方法通常是禁用相关的ESLint规则并使用TypeScript编译器。
TypeScript是JavaScript的超集
即使在解析器中进行了AST转换,最终AST中还是会有ESLint无法理解的事情。如果ESLint规则的编写方式使他们对AST进行了特殊假设,则有时可能会导致规则崩溃。可以通过多种方式缓解这种情况-我们可以与规则作者合作以使他们的代码更健壮,或者可以通过自己的规则提供替代规则[@typescript-eslint/eslint-plugin](https://github.com/typescript-eslint/typescript-eslint/blob/master/packages/eslint-plugin)
项目中关心的几个软件包解析:
请按照下面的链接获取您关心的软件包。
[@typescript-eslint/typescript-estree](https://github.com/typescript-eslint/typescript-eslint/blob/master/packages/typescript-estree)-完全通用的TypeScript解析器,该解析器采用TypeScript源代码并生成与ESTree兼容的AST- 此软件包还用于增强功能强大的代码格式化器Prettier自己的TypeScript用例。
[@typescript-eslint/parser](https://github.com/typescript-eslint/typescript-eslint/blob/master/packages/parser)-特定typescript-estree于ESLint的解析器,该解析器可以利用ESLint的默认解析器,并且可以代替ESLint的默认解析器espree。[@typescript-eslint/eslint-plugin](https://github.com/typescript-eslint/typescript-eslint/blob/master/packages/eslint-plugin)-特定于ESLint的插件,当与结合使用时@typescript-eslint/parser,可以运行特定于TypeScript的插入规则。[@typescript-eslint/eslint-plugin-tslint](https://github.com/typescript-eslint/typescript-eslint/blob/master/packages/eslint-plugin-tslint)-特定于ESLint的插件,可在您的ESLint设置内运行TSLint实例,以使用户可以更轻松地从TSLint迁移到ESLint。
专家提示:对于较大的代码库,您可能需要考虑将linting分为两个单独的阶段:1.快速反馈规则,该规则仅基于语法运行(不进行类型检查); 2.基于语义的规则(进行类型检查)
ESLint 附带有大量的规则。你可以使用注释或配置文件修改你项目中要使用的规则。要改变一个规则设置,你必须将规则 ID 设置为下列值之一:
"off"或0- 关闭规则"warn"或1- 开启规则,使用警告级别的错误:warn(不会导致程序退出)"error"或2- 开启规则,使用错误级别的错误:error(当被触发的时候,程序会退出)
module.exports = {// 将eslint的默认解析器用@typescript-eslint/parser代替parser: '@typescript-eslint/parser',// Eslint团队建议所有项目使用的规则集 eslint:recommended// 启用typescript所有建议的规则:'plugin:@typescript-eslint/recommended'extends: ['eslint:recommended', 'plugin:@typescript-eslint/recommended', "plugin:@typescript-eslint/eslint-recommended"],// 引入typescript转化的eslint插件plugins: ['@typescript-eslint'],// 配置规则rules: {// 关闭 ts/indent,base里面已经配置了 indent// 缩进规则'@typescript-eslint/indent': 0,// 关闭除导入语句外,禁止使用require语句'@typescript-eslint/no-var-requires': 0,// 关闭 在函数和类方法上需要显式的返回类型'@typescript-eslint/explicit-function-return-type': 0,// 在类属性和方法上需要显式可访问性修饰符: public、 private、 protected// 'no-public': 将可访问性设置为“不公开”时'@typescript-eslint/explicit-member-accessibility': [2, { accessibility: 'no-public' }],// 禁止使用 any 类型'@typescript-eslint/no-explicit-any': 1,// 不允许为初始化为数字,字符串或布尔值(无推断类型)的变量或参数进行明确的类型声明。// ignoreParameters忽略方法参数; ignoreProperties: 忽略对象属性定义'@typescript-eslint/no-inferrable-types': [2, { ignoreParameters: true, ignoreProperties: true }],// 要求接口名称应以I为前缀(接口名称前缀)// "never": Equivalent to { "prefixWithI": "never" }// "always": Equivalent to { "prefixWithI": "always" } : 所有的接口都必须以I开头,不允许_I开头'@typescript-eslint/interface-name-prefix': [2, 'always'],// 需要对数组使用T []或Array <T>(数组类型)'@typescript-eslint/array-type': 0,//强制默认参数为最后'@typescript-eslint/default-param-last': 2,// 禁止使用自定义TypeScript模块和名称空间'@typescript-eslint/no-namespace': 0,// 此处由 eslint-config-base 的 no-use-before-define 定义// 在定义变量之前禁止使用变量'@typescript-eslint/no-use-before-define': 0,// 禁止使用特定类型// 可以指定特定的类型由其他类型代替比如 Object由object代替; {}由object代替'@typescript-eslint/ban-types': [2,{types: {Object: {message: 'Use object instead',fixWith: 'object',},'{}': {message: 'Use object instead',fixWith: 'object',},},},],},};
参考文献
typescript使用API可以参考: https://ts.xcatliu.com/
eslint的文件配置规范: https://cn.eslint.org/docs/user-guide/configuring
eslint-rules配置对照表: https://cn.eslint.org/docs/rules/(默认都是关闭所有配置,elint:recommended通用配置开启状态参考对照表)
typescript-eslint配置对照表:https://github.com/typescript-eslint/typescript-eslint/tree/master/packages/eslint-plugin
结束语
本文根据经验总结,观看可以带着问题,应该可以找到对应的答案,具体typescript的Api可以参考官方或者社区文档; 之前与react的结合文章,也有介绍注意点,可以查看; 本文如果对您有帮助,欢迎评论或start;
本文主要是开发中存在的疑问点,或者架构师配置规范,可能存在的不懂知识点;做一个梳理,方便自己查阅;
