Skip to content

常用类型

  • string number boolean
  • array
  • any
    • noImplicitAny
  • function
    • 参数类型注释
      typescript
      function greet(name: string) {
        console.log("Hello, " + name.toUpperCase() + "!!");
      }
    • 返回类型注释
      typescript
      function getFavoriteNumber(): number {
        return 26;
      }
      typescript
      async function getFavoriteNumber(): Promise<number> {
        return 26;
      }
    • 匿名函数
      typescript
      const names = ["Alice", "Bob", "Eve"];
       
      // Contextual typing for function - parameter s inferred to have type string
      names.forEach(function (s) {
        console.log(s.toUpperCase());
      });
  • object
    • 定义对象类型
      typescript
      function printCoord(pt: { x: number; y: number }) {
        console.log("The coordinate's x value is " + pt.x);
        console.log("The coordinate's y value is " + pt.y);
      }
    • 可选属性
      typescript
      function printName(obj: { first: string; last?: string }) {
        // ...
      }
  • 联合类型
    • 定义联合类型
      typescript
        function printId(id: number | string) {
        console.log("Your ID is: " + id);
      }
    • 使用联合类型
      typescript
      function printId(id: number | string) {
        if (typeof id === "string") {
          // In this branch, id is of type 'string'
          console.log(id.toUpperCase());
        } else {
          // Here, id is of type 'number'
          console.log(id);
        }
      }
  • type 类型别名
    typescript
    type Point = {
      x: number;
      y:number;
    }
    typescript
    type ID = number | string;
  • interface
    typescript
    interface Point {
      x: number;
      y: number;
    }
  • 类型断言
    typescript
    const myCanvas = document.getElementById("main_canvas") as HTMLCanvasElement;
    typescript
    const a = expr as any as T;
  • 文字类型
    typescript
    type POSITION = 'left'|'right';
    declare function handleRequest(url: string, method: "GET" | "POST"): void;
  • nullundefined
    • strictNullChecks
    • 非空断言
      typescript
      function liveDangerously(x?: number | null) {
        // No error
        console.log(x!.toFixed());
      }
  • enum 枚举

不常用类型

  • bigint
  • symbol