30分钟学TypeScript
· 阅读需 18 分钟
TypeScript 极简入门。
今天我们要来看看 TypeScript,一个为构建复杂的大型的应用而设计的需要编译成 JavaScript 的语言。它继承了诸多语言比如 C#、Java 的理念,并且在动态类型的 JavaScript 中加入了更多的约束。
这篇教程针对那些能够相对熟练的使用 JavaScript 但是没怎么用过 TypeScript 的人们。教程包含了 TypeScript 最基础和关键的特性并且配合许多带有注释的例子帮助大家理解这门语言。让我们开始吧!
使用 TypeScript 的好处
JavaScript 是一门很不错的语言,以至于很多人会想是否真的有必要去学习 TypeScript。技术上,成为一个优秀的开发者不必要使用 TypeScript,很多用不使用它也做得很好。但是,使用 TypeScript 必定会带来一些好处:
- 得益于静态类型,使用 TypeScript 写的代码有更多的可预测性,调试起来也更加方便。
- 感谢模块、命名空间和强大的面向对象支持,让组织大型复杂的应用代码更加方便。
- TypeScript 编译成 JavaScript 时会捕获错误,这样在运行时就不会打断。
- 即将到来的 Angular 2 框架使用 TypeScript 写的,并且推荐使用 TypeScript。
推荐使用 TypeScript 的最后一点也是主要理由是 Angular 2 是当下最火的框架之一,尽管她可以使用普通的 JavaScript 编写,但是大量的教程和例子用的都是 TypeScript,所以越来越多的人会使用 TypeScript。
安装 TypeScript
需要先安装 Node.js 和 NPM。如果还没有安装它们,请看这里。
最简单的安装 TypeScript 的方式是使用 NPM 。使用下面的命令,我们可以全局的安装 TypeScript 包,让 TS 编译器在所有项目中都可以使用。
npm install -g typescript
打开命令行,在任意地方试着运行 tsc -v 查看有没有正确安装:
tsc -v
Version 1.8.10
编辑器的 TypeScript 支持
TypeScript 是一个开源项目,但是是由微软开发和维护的,所以它在微软的 Visual Studio 平台被原生支持。现在,越来越多的编辑器原生支持或通过插件支持 TypeScript 语法,自动完成提示,错误捕捉甚至是内置编译。
- Visual Studio Code - 微软的一款轻量级开源代码编辑器,内置 TypeScript 支持。
- 官方的 Sublime Text 插件。