学习Typescript (一)
Typescript是什么
TypeScript 是 JavaScript 的一个超集。它是由微软开发的自由和开源的编程语言。设计目标是开发大型应用,它可以编译成纯 JavaScript,编译出来的 JavaScript 可以运行在任何浏览器上。前端学习Typescript逐渐称为趋势。
TypeScript 与 ES5、ES2015 和 ES2016 之间的关系
TypeScript 是 JavaScript 的超集,扩展了 JavaScript 的语法,因此现有的 JavaScript 代码可与 TypeScript 一起工作无需任何修改,TypeScript 通过类型注解提供编译时的静态类型检查。
TypeScript 可处理已有的 JavaScript 代码,并只对其中的 TypeScript 代码进行编译

| TypeScript | JavaScript |
|---|---|
| JavaScript 的超集用于解决大型项目的代码复杂性 | 一种脚本语言,用于创建动态网页。 |
| 可以在编译期间发现并纠正错误 | 只能在运行时发现错误 |
| 强类型,支持静态和动态类型 | 弱类型,没有静态类型选项 |
| 最终被编译成 JavaScript 代码,使浏览器可以理解 | 可以直接在浏览器中使用 |
| 支持模块、泛型和接口 | 不支持模块,泛型或接口 |
| 支持 ES3,ES4,ES5 和 ES6 等 | 不支持编译其他 ES3,ES4,ES5 或 ES6 |
为什么要用Typescript
- TS提供的类型可以帮助在写代码的时候提供更丰富的语法提示。
- 在创建前的编译阶段经过类型系统的检查,就可以避免很多线上的错误.
安装Typescript
使用淘宝镜像源
npm config set registry https://registry.npm.taobao.org
下载
npm install -g typescript
检查安装状态
安装完成之后使用tsc来查看相关命令:
-h, --help Print this message.
-w, --watch Watch input files.
--pretty Stylize errors and messages using color and context (experimental).
--all Show all compiler options.
-v, --version Print the compiler's version.
--init Initializes a TypeScript project and creates a tsconfig.json file.
-p FILE OR DIRECTORY, --project FILE OR DIRECTORY Compile the project given the path to its configuration file, or to a folder with a 'tsconfig.json'.
-b, --build Build one or more projects and their dependencies, if out of date
-t VERSION, --target VERSION Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', 'ES2021', or 'ESNEXT'.
-m KIND, --module KIND Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'.
--lib Specify library files to be included in the compilation.
'es5' 'es6' 'es2015' 'es7' 'es2016' 'es2017' 'es2018' 'es2019' 'es2020' 'es2021' 'esnext' 'dom' 'dom.iterable' 'webworker' 'webworker.importscripts' 'webworker.iterable' 'scripthost' 'es2015.core' 'es2015.collection' 'es2015.generator' 'es2015.iterable' 'es2015.promise' 'es2015.proxy' 'es2015.reflect' 'es2015.symbol' 'es2015.symbol.wellknown' 'es2016.array.include' 'es2017.object' 'es2017.sharedmemory' 'es2017.string' 'es2017.intl' 'es2017.typedarrays' 'es2018.asyncgenerator' 'es2018.asynciterable' 'es2018.intl' 'es2018.promise' 'es2018.regexp' 'es2019.array' 'es2019.object' 'es2019.string' 'es2019.symbol' 'es2020.bigint' 'es2020.promise' 'es2020.sharedmemory' 'es2020.string' 'es2020.symbol.wellknown' 'es2020.intl' 'es2021.promise' 'es2021.string' 'es2021.weakref' 'esnext.array' 'esnext.symbol' 'esnext.asynciterable' 'esnext.intl' 'esnext.bigint' 'esnext.string' 'esnext.promise' 'esnext.weakref'
--allowJs Allow javascript files to be compiled.
--jsx KIND Specify JSX code generation: 'preserve', 'react-native', 'react', 'react-jsx' or 'react-jsxdev'.
-d, --declaration Generates corresponding '.d.ts' file.
--declarationMap Generates a sourcemap for each corresponding '.d.ts' file.
--sourceMap Generates corresponding '.map' file.
--outFile FILE Concatenate and emit output to single file.
--outDir DIRECTORY Redirect output structure to the directory.
--removeComments Do not emit comments to output.
--noEmit Do not emit outputs.
--strict Enable all strict type-checking options.
--noImplicitAny Raise error on expressions and declarations with an implied 'any' type.
--strictNullChecks Enable strict null checks.
--strictFunctionTypes Enable strict checking of function types.
--strictBindCallApply Enable strict 'bind', 'call', and 'apply' methods on functions.
--strictPropertyInitialization Enable strict checking of property initialization in classes.
--noImplicitThis Raise error on 'this' expressions with an implied 'any' type.
--alwaysStrict Parse in strict mode and emit "use strict" for each source file.
--noUnusedLocals Report errors on unused locals.
--noUnusedParameters Report errors on unused parameters.
--noImplicitReturns Report error when not all code paths in function return a value.
--noFallthroughCasesInSwitch Report errors for fallthrough cases in switch statement.
--types Type declaration files to be included in compilation.
--esModuleInterop Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'.
@<file>
编译ts文件
命令 tsc + 文件名
echo const str1: string = 'vincent' > 01.ts
tsc 01.ts
//ts
const str: string = "vincent";
//编译后的js=>01.js
var str1 = 'vincent';
编译tsc 01.ts


TypeScript 转换为 JavaScript 过程如下图:

Typescript 数据类型
基本类型
String类型
使用string表示文本数据类型。 和JavaScript一样,可以使用双引号"或单引号' `表示字符串。
const str: string = 'vincent';
const name: string = 'chen';
const fullname: string = `${str} ${name}`;
Boolean类型
最基本的数据类型就是简单的true/false值,在JavaScript和TypeScript里叫做boolean(其它语言中也一样)。
const isY: boolean = false;
Number类型
TypeScript里的所有数字都是浮点数。 这些浮点数的类型是number。 除了支持十进制和十六进制字面量,TypeScript还支持ECMAScript 2015中引入的二进制和八进制字面量。
let binaryLiteral: number = 0b1010; // 二进制
let octalLiteral: number = 0o744; // 八进制
let decLiteral: number = 6; // 十进制
let hexLiteral: number = 0xf00d; // 十六进制
Array类型
有两种方式可以定义数组。
- 第一种可以在元素类型后面接上[],表示由此类型元素组成的一个数组
- 第二种方式是使用数组泛型,Array<元素类型>
// 在元素类型后面加上[]
const arr1: number[] = [1, 2];
// 或者使用数组泛型
const arr2: Array<number> = [1, 2];
Enum 类型
元组 Tuple
元组类型用来表示已知元素数量和类型的数组,各元素的类型不必相同,对应位置的类型需要相同
// Declare a tuple type
let x: [string, number];
x = ['vincent', 1]; // OK
x = [1, 'vincent']; // Error

浙公网安备 33010602011771号