Typescript 入门

27 阅读2分钟

一、Typescript 介绍

1.TypeScript 是由微软开发的一款开源的编程语言。

2、 TypeScript 是 Javascript 的超集,遵循最新的 ES6、Es5 规范。TypeScript 扩展了 JavaScript

的语法。

3.TypeScript 更像后端 java、C#这样的面向对象语言可以让 js 开发大型企业项目。

4、谷歌也在大力支持 Typescript 的推广,谷歌的 angular2.x+就是基于 Typescript 语法。

5、最新的 Vue 、React 也可以集成 TypeScript。

image-20200129224110123

二、 Typescript 安装 编译

npm install -g typescript
tsc helloworld.ts

输完命令之后会生成一个 js 文件,es5 语法

三、Typescript 开发工具 Vscode 自动编译.ts 文件

1.创建 tsconfig.json 文件 tsc --init 生成配置文件 tsconfig.json (删掉了无关配置代码)

改 "outDir": "./js",

{
  "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'. */
    "outDir": "./js",                        /* Redirect output structure to the directory. */
​
    /* Strict Type-Checking Options */
    "strict": true,                           /* Enable all strict type-checking options. */
​
    // "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'. */
  }
}

2、点击菜单 任务-运行任务

点击 tsc:监视-tsconfig.json 然后就可以自动生成代码了

image-20200129224642069

3.案例

比如这个代码,使用 TS 语法,

console.log('你好ts')
var str: string = '你好ts'
function getData() {
  return 'ts'
}

编译之后生成的代码

console.log('你好ts')
var str = '你好ts'
function getData() {
  return 'ts'
}

四、Typescript 开发工具 HBuilder 自动编译.ts 文件 (没试验过,具体看文档)

1.在最上方菜单栏,点击工具-插件安装;

2.点击下方浏览 Eclipse 插件市场,搜索 typescript 插件进行安装

3.安装完成后重启编译器,点击菜单栏工具-选项 选择编译 ts 文件

4.在你的项目上右键点击--配置--Enable TypeScript Builder,之后你再保存.ts 文件

时会自动在当前目录编译出对应的.js 文件

五、typeScript 中的数据类型

typescript 中为了使编写的代码更规范,更有利于维护,增加了类型校验,在 typescript 中主要给我们提供了以下数据类型

布尔类型(boolean)

数字类型(number)

字符串类型(string)

数组类型(array)

元组类型(tuple)

枚举类型(enum)

任意类型(any)

null 和 undefined

void 类型

never 类型