🪜 typescript学习笔记【第一课】认识和使用

176 阅读1分钟

🔍 what is typescript

JavaScript and More

TypeScript adds additional syntax to JavaScript to support a tighter integration with your editor. Catch errors early in your editor.

  • TypeScript为JavaScript添加了额外的语法,来支持与编辑器更紧密的集成。在编辑器的早期捕获错误。

A Result You Can Trust

TypeScript code converts to JavaScript which runs anywhere JavaScript runs: In a browser, on Node.js or Deno and in your apps.

  • TypeScript代码可以转换为JavaScript,在JavaScript运行的任何地方运行: 在浏览器中,在Node.js 或 Deno上,更或者是在你的应用程序中。

Safety at Scale

TypeScript understands JavaScript and uses type inference to give you great tooling without additional code.

  • TypeScript理解JavaScript,并使用类型推断为你提供了很棒的工具,而不需要额外的代码。

安装 typescript

安装

# npm
npm install typescript -D
# yarn 
yarn add typescript -D

运行 typescript 编译器

npx tsc
或
yarn tsc

🔧 tsconfig.json 配置

The presence of a tsconfig.json file in a directory indicates that the directory is the root of a TypeScript project. The tsconfig.json file specifies the root files and the compiler options required to compile the project.

  1. 手动创建 tsconfig.json 内容为 {}
  2. 自动生成 npx tsc --init

tsconfig.json文件在TypeScript项目的根目录下,指定编译项目所需的根文件和编译器选项。TypeScript 将会把包含此tsconfig.json文件的目录和子目录下的所有 .ts 文件作为编译上下文的一部分。

{
  "compilerOptions": {},
  "files": [
    "src/hello.ts"
  ],
  "include": [
    "src/**/*.ts"
  ],
  "exclude": [
    "node_modules"
  ]
}
  • compilerOptions 配置编译选项
  • files 显式指定需要编译的文件
  • include 包含的文件
  • exclude 排除的文件

其中路径和文件支持通配符,其中 **/* 表示所有路径下的所有文件

编译ts文件

编译的过程就是将ts文件转化成js文件

  1. 编译制定文件 npx tsc hello.ts
  2. 根据配置文件编译 npx tsc --init npx tsc
  3. 监听文件变化自动编译 npx tsc -w filePath