typescript 学习资源 typescript 官网 源码地址 TypeScript 是什么及特点 Typescript 是 javascript 的一个超集,提供了类型系统和对 ES6 的支持 可以编译成 javascript 写代码的时候进行了类型定义,可以在编译阶段发现错误 文件后缀为.ts,拿 typescript 编写 react 时后缀是.tsx 如何安装 hello world…

TypeScript 是什么及特点

  1. Typescript 是 javascript 的一个超集,提供了类型系统和对 ES6 的支持
  2. 可以编译成 javascript
  3. 写代码的时候进行了类型定义,可以在编译阶段发现错误
  4. 文件后缀为.ts,拿 typescript 编写 react 时后缀是.tsx

如何安装

# 安装
npm install -g typescript
# 查看版本
tsc -v
# 编译
tsc 1.ts

hello world

// 00.ts
// 如何sayHello传的是非字符串类型,那么在编译时就会报错
function sayHello(person: string) {
  console.log('hello ' + person);
}
sayHello('world');
tsc 00.ts

tsconfig.json

用来编译这个项目的根文件和编译选项

  1. 指定编译文件有两种方式:files 与 include/exclude
  2. 如果 files 和 include 都未设置,除了 exclue 排除的文件,编辑器会默认包含路径下的所有 ts 文件
  3. 如果同时设置 files 和 include 属性,那么编辑器会把两者指定的文件都引入
  4. 如果未设置 exclude 属性,默认值为 node_modules 、bower_components、jspm_packages 和编译选项 outDir 指定的路径
  5. exclude 排出的文件正好是 files 指定的文件,那么该文件依旧会被编译
  6. tsconfig.json 文件不存在或者为空,会使用默认编译选项来编译所有引入的文件
  7. 具体参数含义

files

files 属性是一个数组,可以是相对文件路径或者绝对文件路径

{
  // 配置编译选项
  "compilerOptions": {
    // 生成的模块形式
    "module": "commonjs",
    // 存在隐式 any 时抛错
    "noImplicitAny": true,
    // 移除注释
    "removeComments": true,
    "preserveConstEnums": true,
    // 生成 .map 文件
    "sourceMap": true
  },
  // 指定编译文件
  "files": ["00.ts"]
}

include/exclude

include/exclude 属性是一个数组,支持通配符匹配文件

* :匹配 0 或多个字符(注意:不含路径分隔符)
? :匹配任意单个字符(注意:不含路径分隔符)
**/ :递归匹配任何子路径
{
  "compilerOptions": {
    "module": "commonjs",
    "noImplicitAny": true,
    "removeComments": true,
    "preserveConstEnums": true,
    "sourceMap": true
  },
  "include": ["*"],
  "exclude": []
}

暂无评论