起步

搭建 TypeScript 开发环境

  • 什么是 compiler?
  • less 编译器:less
  • EcmaScript 6 编译器:babel
  • TypeScript 编译器:typescript
  • 一句话:把 TypeScript 转换为 JavaScript ,浏览器就具有运行了
  • 在线测试编译环境 compiler
  • 本地开发编译环境
  1. npm i -g typescript
  2. # 查看版本号
  3. tsc --version
  4. # 查看使用帮助
  5. tsc --help

编辑器的选择

  • Visual Studio Code
  • Sublime
  • Webstorm

Hello World

新建 greeter.ts 并写入以下内容:

  1. function greeter(person) {
  2. return "Hello, " + person;
  3. }
  4. let user = "Jane User";
  5. document.body.innerHTML = greeter(user);

安装编译器:

  1. npm i -g typescript

编译:

  1. tsc greeter.ts

修改 greeter.ts 文件中的代码,为 greeter 函数的参数 person 加上类型声明 :string

  1. function greeter(person: string) {
  2. return "Hello, " + person;
  3. }
  4. let user = "Jane User";
  5. document.body.innerHTML = greeter(user);

重新编译执行。

让我们继续修改:

  1. function greeter(person: string) {
  2. return "Hello, " + person;
  3. }
  4. let user = [0, 1, 2];
  5. document.body.innerHTML = greeter(user);

重新编译,你将看到如下错误:

  1. error TS2345: Argument of type 'number[]' is not assignable to parameter of type 'string'.

接口(Interface)

  1. interface Person {
  2. firstName: string;
  3. lastName: string;
  4. }
  5. function greeter(person: Person) {
  6. return "Hello, " + person.firstName + " " + person.lastName;
  7. }
  8. let user = { firstName: "Jane", lastName: "User" };
  9. document.body.innerHTML = greeter(user);

类(Class)

  1. class Student {
  2. fullName: string;
  3. constructor(public firstName: string, public middleInitial: string, public lastName: string) {
  4. this.fullName = firstName + " " + middleInitial + " " + lastName;
  5. }
  6. }
  7. interface Person {
  8. firstName: string;
  9. lastName: string;
  10. }
  11. function greeter(person : Person) {
  12. return "Hello, " + person.firstName + " " + person.lastName;
  13. }
  14. let user = new Student("Jane", "M.", "User");
  15. document.body.innerHTML = greeter(user);