简单了解一下,好像前端基本都会面基这个

44 阅读2分钟

一、TypeScript简介

TypeScript是由Microsoft开发的开源编程语言,作为JavaScript的超集,它添加了静态类型系统和对ES6+特性的支持,旨在提升代码可维护性和开发效率。它的优势在于通过类型注解实现编译时类型检查,减少运行时错误,同时保留JavaScript的灵活性。

二、环境搭建与配置

  1. 安装依赖‌:

    • 需先安装Node.js和npm(Node.js包管理器),用于运行TypeScript编译器。

    • 通过npm全局安装TypeScript编译器:

      npm install -g typescript
      

      安装后验证版本:tsc --version

  2. 项目初始化‌:

    • 创建tsconfig.json配置文件:

      tsc --init
      
    • 关键配置示例(支持模块化与现代语法):

      {
        "compilerOptions": {
          "target": "ESNext",
          "module": "ESNext",
          "strict": true,
          "outDir": "./dist"
        },
        "include": ["src/**/*.ts"]
      }
      

      此配置启用严格类型检查,并指定输出目录。

  3. 开发工具‌:

    • 推荐使用Visual Studio Code(VSCode),安装TypeScript插件以增强代码提示和调试功能。

三、核心语法与类型系统

  1. 基础数据类型‌:

    • booleannumberstring等基本类型:

      let isDone: boolean = false;
      let count: number = 10;
      let name: string = "TypeScript";
      
    • 特殊类型:any(动态类型)、void(无返回值)、null/undefined

  2. 复合类型‌:

    • 数组‌:let list: number[] = [1, 2, 3] 或 Array<number>

    • 元组(Tuple) ‌:固定类型顺序的数组,如 let x: [string, number] = ["hello", 10]

    • 枚举(Enum) ‌:定义命名常量集:

      enum Role { Admin, Editor, Viewer }
      let user: Role = Role.Admin;
      ```:ml-citation{ref="3,4" data="citationList"}。  
      
  3. 函数与接口‌:

    • 函数类型注解:

      function add(x: number, y: number): number {
        return x + y;
      }
      
    • 接口(Interface)定义对象结构:

      interface User {
        id: number;
        name: string;
        roles?: string[]; // 可选属性
      }
      const user: User = { id: 1, name: "Alice" };
      ```:ml-citation{ref="3,4" data="citationList"}。  
      
  4. 类与面向对象‌:

    • 支持类、继承、访问修饰符(publicprivate):

      class Animal {
        constructor(public name: string) {}
        move(distance: number = 0) {
          console.log(`${this.name} moved ${distance}m.`);
        }
      }
      class Dog extends Animal {
        bark() {
          console.log("Woof!");
        }
      }
      ```:ml-citation{ref="4,6" data="citationList"}。  
      

四、高级特性

  1. 泛型(Generics) ‌:

    • 创建可复用组件,支持多种类型:

      typescriptCopy Code
      function identity<T>(arg: T): T {
        return arg;
      }
      let output = identity<string>("hello");
      ```:ml-citation{ref="4,6" data="citationList"}。  
      
  2. 模块(Modules) ‌:

    • 使用exportimport组织代码:

      // utils.ts
      export function log(message: string) {
        console.log(message);
      }
      // app.ts
      import { log } from './utils';
      log("Module loaded");
      ```:ml-citation{ref="3,5" data="citationList"}。  
      
  3. 类型守卫与高级类型‌:

    • 类型守卫(如typeofinstanceof)缩小变量类型范围。
    • 映射类型(Mapped Types)和条件类型(Conditional Types)用于复杂类型转换。

五、编译与调试实践

  1. 编译运行‌:

    • 单文件编译:tsc filename.ts 生成同名JS文件。
    • 监控模式:tsc -p tsconfig.json --watch 自动编译变更。
  2. 调试技巧‌:

    • 使用ts-node直接运行TS文件:

      npm install -g ts-node
      ts-node src/app.ts
      ```:ml-citation{ref="3" data="citationList"}。  
      
    • 类型断言处理不确定值:let el = document.getElementById("root") as HTMLDivElement