5分钟使用 TypeScript 构建一个简单的 Web 应用程序

79 阅读1分钟

安装 TypeScript

有两种主要方法可以让 TypeScript 可用于您的项目:

  1. 通过 npm(Node.js 包管理器)

    1.  npm install -g typescript
      
  2. 通过安装 TypeScript 的 Visual Studio 插件

    1. Visual Studio 2017 和 Visual Studio 2015 Update 3 默认包含 TypeScript 语言支持,但不包含 TypeScript 编译器,tsc. 如果你没有使用 Visual Studio 安装 TypeScript,你仍然可以下载它。

构建第一个 TypeScript 文件

输入以下 JavaScript 代码greeter.ts

function greeter(person: string) {
  return "Hello, " + person;
}
 
let user = "Jane User";
 
document.body.textContent = greeter(user);

在命令行中,运行 TypeScript

tsc COMMAND LINE FLAGS

     --help, -h  Print this message.

    --watch, -w  Watch input files.

          --all  Show all compiler options.

  --version, -v  Print the compiler's version.

         --init  Initializes a TypeScript project and creates a tsconfig.json file.

  --project, -p  Compile the project given the path to its configuration file, or to a folder with a 'tsconfig.json'.

    --build, -b  Build one or more projects and their dependencies, if out of date

   --showConfig  Print the final configuration instead of building.
tsc greeter.ts

结果将是一个greeter.js包含您输入的相同 JavaScript 的文件。我们在 JavaScript 应用程序中使用 TypeScript 启动并运行!

function greeter(person) {
    return "Hello, " + person;
}
var user = "Jane User";
document.body.textContent = greeter(user);

输入以下内容greeter.html

<!DOCTYPE html>
<html>
  <head>
    <title>TypeScript Greeter</title>
  </head>
  <body>
    <script src="greeter.js"></script>
  </body>
</html>

在浏览器中打开greeter.html以运行您的第一个简单的 TypeScript Web 应用程序!

总结

在这里简单使用了函数参数的一个类型定义,string。并通过tsc命令,将我们定义的ts文件转化成js文件,并在浏览器中运行。这里就有问题了,你怎么知道要这样定义的呢?肯定是有手册或者文档的。在下一篇中,会将Ts的类型系统,做一个实践。

官网地址

typescript

typescript手册