typescript代码与 javascript 代码有非常高的兼容性,无门槛,你把 js 代码改为 ts 就可以运行。如果没有接触过强类型的编程语言,导致他们认为学习ts需要定义各种类型,还有一些新概念等等,会增加学习成本。typescript 应该不会脱离 javascript 成为独立的语言。学习 typescript 应该主要指的是学习它的类型系统。
什么是 typescript
微软发布了一款 javascript 超集的编程语言并取名为 typescript,由于 typescript 是 javascript 的严格超集,因此任何 javascript 都是合法的 typescript(非常像 c 和 objective-c 的关系)。typescript 为 javascript 带来了强大的类型系统和对 es2015的支持,它的编译工具可以运行在任何服务器和任务系统上。
事实上 es2015 发布之后 javascript 取得了巨大的进步,但随着设备性能的提升以及 javascript 在应用层上不断占据了重要的位置,对于大型项目,人们显然需要更强大的语言级别的支持(微软发现外部客户在开发大规模 javascript 应用的过程中遭遇的语言本身的短板)。
类型系统实际上是非常好的文档,增强了编辑器在 智能提示,跳转定义,代码补全 等方向上的功能,并且在编译阶段能发现大部分的错误,对于大型工程的代码可读性和可维护性起到了了不起的作用。
typescript 的流行趋势
事实上 typescript 拥有活跃的社区,大部分第三方库都有提供 typescript 类型定义文件,甚至知名的前端库都完全使用 typescript 来进行开发,比如 google 的 angular,我们可以通过一些数据来了解 typescript 的流行趋势:

typescript 的优势和收益是什么
typescript 官网上列了很多它的优势,在这里我更愿意自己总结一下:
- 类型系统可在编译阶段发现大部分的错误
- 类型系统也是一个很直观的编程文档,可以查看任何函数或api的输入输出类型
- 类型系统增强了编辑器或ide的功能
- typescript 可以自动的推导类型
- 一切 javascript 都是合法的 typescript 降低了使用成本
- typescript 拥抱 es2015 以及 esnext 草案规范
- 几乎第三方库都有 typescript 类型定义文件
如果你有一个需要长期维护的工程,那么类型系统在可读性和可维护性上拥有比 javascript 更强大的动能,在良好的编程语境下,在稳定的工具链帮助下,typescript 可以说是目前唯一较好的选择。
当然,凡事都有两面性,typescript 有一定的学习成本,比如:interfaces,generics,enums 等前端工程师不是很熟悉的概念,短期内多少会增加一些开发成本,集成和构建一些库会有一定的工作量,比如我们用 react 来开发一个前端工程,那么你就需要进行一些配置,当然你也可以直接使用 create-react-app 来创建一个 typescript + react 工程。
typescript 与 javascript 对比表格
| 对比项目 | typescript | javascript | 注意 | | --------| --- | --- | --- | | 基本类型 | boolean number string array tuple enum any void null undefined never object | string number boolean null undefined symbol | typescript 中 object 表示的是不是 javascript 基本类型的类型| | 变量声明 | let const var| let const var | 基本一致 | | 接口 | interface | 无 | typescript 的核心是类型检查,因此接口充当了命名这些类型的角色 | | 类 | class abstract class readonly … | class 无 abstract class | 基本一致,但不同的可能发生在未来,typescript 使用 private 来定义私有,而 javascript 未来极有可能将 #.xx 来定义私有写入标准。typescript 支持抽象类,只读等等。| | 函数 | n | n | 基本一致,参数赋默认值,剩余参数等等,唯一不同的是 typescript 支持?可选参数 | | 泛型 | generics | 无 | 泛型是一个特别灵活的可重用指定不同类型来控制具体类型的类型,typescript 支持 | | 枚举 | enums | 无 | typescript 支持的枚举不仅可以默认从 0 开始,也可以赋值具体的字符串,它的操作空间非常大 | | 类型推断 | 支持 | 无 | let x = 3; typescript 可以通过 3 来推断 x 的类型是 number | | 高阶类型 | & typeof instanceof … | 无 | typescript 独有 | | symbols | n | n | symbol 一样 | | 迭代器 | n | n | 如果实现了 symbol.iterator ,那么就被视为可迭代的,术语上和 javascript 定义的一样 | | generators | n | n | 一样 | | 模块系统 | n | export import | 事实上 typescript 支持多种多样的模块系统,既有 esmodule 也有 commonjs 规范,甚至还有 amd umd 等 | | 其他 | n | n | 由于 typescript 是 javascript 的超集,因此 es2016 之后以及 esnext 定义的 api 都可以直接在 typescript 中使用 并不需要语言支持,至于其他一些比如 jsx mixins 等等,由于这些不属于 javascript 标准因此这里不再复述 。|
环境配置
typescript 3.3
既然上文我们了解到 typescript 需要编译,那么我们肯定会使用到编译工具,因此在我们开始正式学习 typescript 之前需要安装一下编译环境。
- 安装 node.js 10.15.3 lts
- 安装 typescript
$ npm install -g typescript $ tsc --version
国际惯例 hello world
创建一个 helloworld.ts 文件,然后输入:
let helloworld = ""; console.log(helloworld); $ tsc helloworld.ts
现在我们稍微改动一行代码,在 javascript 中我们完全可以如此:
let helloworld = ""; helloworld = 1;
对于语法而言这完全是正确的,但对于语句来说,不能锁定类型在某些情况下,很容易出现未知异常的问题,现在我们执行 tsc 来编译它:
$ tsc helloworld.ts helloworld.ts:5:1 - error ts2322: type '1' is not assignable to type 'string'. 5 helloworld = 1; found 1 error.
编译器可以明确的告知你不能将 1 赋值给字符串类型,这就是 typescript 带来的魅力。
tsconfig.json
tsconfig.json 文件可以指定编译 typescript 项目所需的根目录以及编译器选项,如果你的工程中存在 tsconfig.json 则表示 tsconfig.json 所在的目录为你 typescript 工程的根目录。
使用 tsconfig.json 的规则:
- 如果你直接运行
tsc在这种情况下,编译器将从当前目录开始搜索tsconfig.json并向上查找 - 你也可以直接运行
tsc -p xxx在这种情况下,xxx 目录上必须存在tsconfig.json文件 - 如果在命令行中直接输出文件
tsc helloworld.ts编译器将忽略tsconfig.json文件
当然你可以直接使用 tsc --init 在当前运行的目录中创建一个 tsconfig.json(推荐)。
{
"compileroptions": {
/* basic options */
"target": "es5", /* specify ecmascript target version: 'es3' (default), 'es5', 'es2015', 'es2016', 'es2017','es2018' or 'esnext'. */
"module": "commonjs", /* specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'esnext'. */
// "lib": [], /* specify library files to be included in the compilation. */
// "allowjs": true, /* allow javascript files to be compiled. */
// "checkjs": true, /* report errors in .js files. */
// "jsx": "preserve", /* specify jsx code generation: 'preserve', 'react-native', or 'react'. */
// "declaration": true, /* generates corresponding '.d.ts' file. */
// "declarationmap": true, /* generates a sourcemap for each corresponding '.d.ts' file. */
// "sourcemap": true, /* generates corresponding '.map' file. */
// "outfile": "./", /* concatenate and emit output to single file. */
// "outdir": "./", /* redirect output structure to the directory. */
// "rootdir": "./", /* specify the root directory of input files. use to control the output directory structure with --outdir. */
// "composite": true, /* enable project compilation */
// "removecomments": true, /* do not emit comments to output. */
// "noemit": true, /* do not emit outputs. */
// "importhelpers": true, /* import emit helpers from 'tslib'. */
// "downleveliteration": true, /* provide full support for iterables in 'for-of', spread, and destructuring when targeting 'es5' or 'es3'. */
// "isolatedmodules": true, /* transpile each file as a separate module (similar to 'ts.transpilemodule'). */
/* strict type-checking options */
"strict": true, /* enable all strict type-checking options. */
// "noimplicitany": true, /* raise error on expressions and declarations with an implied 'any' type. */
// "strictnullchecks": true, /* enable strict null checks. */
// "strictfunctiontypes": true, /* enable strict checking of function types. */
// "strictbindcallapply": true, /* enable strict 'bind', 'call', and 'apply' methods on functions. */
// "strictpropertyinitialization": true, /* enable strict checking of property initialization in classes. */
// "noimplicitthis": true, /* raise error on 'this' expressions with an implied 'any' type. */
// "alwaysstrict": true, /* parse in strict mode and emit "use strict" for each source file. */
/* additional checks */
// "nounusedlocals": true, /* report errors on unused locals. */
// "nounusedparameters": true, /* report errors on unused parameters. */
// "noimplicitreturns": true, /* report error when not all code paths in function return a value. */
// "nofallthroughcasesinswitch": true, /* report errors for fallthrough cases in switch statement. */
/* module resolution options */
// "moduleresolution": "node", /* specify module resolution strategy: 'node' (node.js) or 'classic' (typescript pre-1.6). */
// "baseurl": "./", /* base directory to resolve non-absolute module names. */
// "paths": {}, /* a series of entries which re-map imports to lookup locations relative to the 'baseurl'. */
// "rootdirs": [], /* list of root folders whose combined content represents the structure of the project at runtime. */
// "typeroots": [], /* list of folders to include type definitions from. */
// "types": [], /* type declaration files to be included in compilation. */
// "allowsyntheticdefaultimports": true, /* allow default imports from modules with no default export. this does not affect code emit, just typechecking. */
"esmoduleinterop": true /* enables emit interoperability between commonjs and es modules via creation of namespace objects for all imports. implies 'allowsyntheticdefaultimports'. */
// "preservesymlinks": true, /* do not resolve the real path of symlinks. */
/* source map options */
// "sourceroot": "", /* specify the location where debugger should locate typescript files instead of source locations. */
// "maproot": "", /* specify the location where debugger should locate map files instead of generated locations. */
// "inlinesourcemap": true, /* emit a single file with source maps instead of having a separate file. */
// "inlinesources": true, /* emit the source alongside the sourcemaps within a single file; requires '--inlinesourcemap' or '--sourcemap' to be set. */
/* experimental options */
// "experimentaldecorators": true, /* enables experimental support for es7 decorators. */
// "emitdecoratormetadata": true, /* enables experimental support for emitting type metadata for decorators. */
}
}编译器选项
这些编译器选项也是 tsconfig.json 中的配置项
当你不想通过 tsconfig.json 来配置编译器的话,也可以使用如下的编译器选项通过命令行来运行编译器执行编译任务,这里只介绍几个常用的,其他的配置请参考 compiler options 表格。
--watch 或 -w监视输入文件的更改并触发重新编译--version 或 -v查看编译器的版本--types=["字符串"]类型描述文件的名称列表--target=""指定编译的 ecmascript 的版本,默认版本是 es3--strict启用所有严格类型检查--sourcemap生成对应的 .map 文件--outfile输出到单个文件--outdir输出到目录--module 或 -m指定使用哪种模块标准来输出代码,选项有 "none", "commonjs", "amd", "system", "umd", "es6", "es2015" or "esnext"--lib要包含在编译中的库文件列表,比如 es2015.promise--jsx在.tsx文件中支持jsx可指定要编译输出的jsx类型
与 webpack 集成
事实上我们不可能只单独的使用 typescript 而是要将它融入到现有的技术栈中和工具结合起来,至少目前为止多数的前端工程都将 webpack 视为标准配置,因此 typescript 编译器和 webpack 集成在一起,这非常有用。
awesome-typescript-loader 是 typescript 提供的在 webpack 中使用的 loader,因此我们只需要:
$ yarn add typescript awesome-typescript-loader source-map-loader --dev
然后在你的 webpack.config.json 文件中配置即可:
var fs = require('fs')
var path = require('path')
var webpack = require('webpack')
const { checkerplugin } = require('awesome-typescript-loader');
var root = path.resolve(__dirname)
module.exports = {
entry: './src/index.tsx',
devtool: 'inline-source-map',
output: {
path: root + '/dist',
filename: '[name].bundle.js',
sourcemapfilename: '[name].bundle.map.js',
publicpath: '//localhost:8889/dist/',
},
devserver: {
inline: true,
quiet: true,
contentbase: "./",
port: 8889
},
module: {
rules: [
{ test: /\.ts[x]?$/, loader: "awesome-typescript-loader" },
{ enforce: "pre", test: /\.ts[x]$/, loader: "source-map-loader" },
]
},
resolve: {
extensions: [".ts", ".tsx"],
alias: {
'@': path.resolve(root,'src')
}
},
plugins: [
new checkerplugin(),
]
}
结语
这篇文章简单介绍了 该怎么学typescript,有一句古话:了解历史才能真正了解这些故事,时代变化 javascript 可以说是目前为止唯一实现了 write once run anywhere 的脚本语言(当然 c 语言才是),它的热度和趋势长久不衰,但 javascript 本身也有其语言的缺陷,也许在未来新的标准会慢慢补齐它,至少现在让我们用 typescript 来解决你可能面临的问题吧。
到此这篇关于typescript难学吗?前端有必要学?该怎么学typescript的文章就介绍到这了,更多相关前端学typescript内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论