类型系统

  1. 在开发过程中找错
  2. 使用“类型注解”来分析代码
  3. 仅存在于开发阶段
  4. 不会提供性能优化,JavaScript写完可以通过工具进行性能优化

    编译过程

  5. TypeScript代码

  6. TypeScript编译器
  7. JavaScript代码
  8. 机器码
  9. 浏览器运行机器码

    安装

    1. npm install -g typescript ts-node

    测试是否安装成功

    1. tsc --help

    返回:tsc: The TypeScript Compiler - Version 4.5.5

    初始化

    1. npm init
    2. npm install axios

    TS代码

    1. import axios from 'axios'
    2. const url = "https://jsonplaceholder.typicode.com/todos/1";
    3. console.log(axios.get(url).then(res=>{
    4. console.log(res);
    5. }));

    typescriptJavaScript

    1. tsc .\index.ts
    2. node index.js

    或者直接转换并执行

    1. ts-node .\index.ts

    类型注解

    1. import axios from 'axios'
    2. const url = "https://jsonplaceholder.typicode.com/todos/1";
    3. // 接口
    4. interface Todo {
    5. id: number;
    6. title: string;
    7. completed: boolean;
    8. }
    9. // 请求
    10. axios.get(url).then(res => {
    11. // 类型 interface Todo
    12. const todo = res.data as Todo;
    13. const id = todo.id;
    14. const title = todo.title;
    15. const completed = todo.completed;
    16. logTodo(id, title, completed);
    17. });
    18. // 模板打印
    19. const logTodo = (id: number, title: string, completed: boolean) => {
    20. console.log(`
    21. 这个todo的ID为:${id},
    22. 它的标题是:${title},
    23. 是否完成:${completed}
    24. `);
    25. }

    类型分类

    元类型

    primitive types

  10. number

  11. boolean
  12. undefined
  13. void
  14. string
  15. symbol
  16. null

    对象类型

    object types

  17. function

  18. arrays
  19. classes
  20. objects

    类型的副作用

    typescript中如果你未设置类型,那么会根据你定义的数据进行类型审查,帮你选择一个类型。