编程·

TypeScript速查表

一份 TypeScript 速查表,包含最重要的概念、函数、方法等。为初学者提供完整的快速参考。

入门

安装编译器

npm install typescript --save-dev
npm tsc

基本数据类型

基本类型

let isDone: boolean = false;
let age: number = 30;
let userName: string = "John";
let list: number[] = [1, 2, 3];
let tuple: [string, number] = ["hello", 10];
let notSure: any = 4;
notSure = "可能是一个字符串";

枚举

enum Color {
  Red,
  Green,
  Blue,
}
let c: Color = Color.Green;

接口

interface Person {
  firstName: string;
  lastName: string;
  age?: number; // 可选属性
}

function greet(person: Person) {
  return "你好, " + person.firstName + " " + person.lastName;
}

函数

function add(x: number, y: number): number {
  return x + y;
}

let myAdd = function (x: number, y: number): number {
  return x + y;
};

let myArrowAdd = (x: number, y: number): number => x + y;

function buildName(firstName: string, lastName = "Smith") {
  return firstName + " " + lastName;
}

function buildFullName(firstName: string, ...restOfName: string[]) {
  return firstName + " " + restOfName.join(" ");
}

class Greeter {
  greeting: string;
  constructor(message: string) {
    this.greeting = message;
  }
  greet() {
    return "你好, " + this.greeting;
  }
}

let greeter = new Greeter("世界");

继承

class Animal {
  move(distance: number = 0) {
    console.log(`动物移动了 ${distance} 米。`);
  }
}

class Dog extends Animal {
  bark() {
    console.log("汪! 汪!");
  }
}

const dog = new Dog();
dog.bark();
dog.move(10);
dog.bark();

泛型

function identity<T>(arg: T): T {
  return arg;
}

let output1 = identity<string>("myString");
let output2 = identity<number>(42);

类型断言

let someValue: any = "this is a string";
let strLength: number = (<string>someValue).length;
// or
let strLength2: number = (someValue as string).length;

模块

导出

export interface StringValidator {
  isAcceptable(s: string): boolean;
}

export class ZipCodeValidator implements StringValidator {
  isAcceptable(s: string) {
    return s.length === 5;
  }
}

导入

import { ZipCodeValidator } from "./ZipCodeValidator";

let myValidator = new ZipCodeValidator();

命名空间

namespace Validation {
  export interface StringValidator {
    isAcceptable(s: string): boolean;
  }

  export class LettersOnlyValidator implements StringValidator {
    isAcceptable(s: string) {
      return /^[A-Za-z]+$/.test(s);
    }
  }
}

let validator = new Validation.LettersOnlyValidator();

联合类型和交叉类型

联合类型

function padLeft(value: string, padding: string | number) {
  if (typeof padding === "number") {
    return Array(padding + 1).join(" ") + value;
  }
  if (typeof padding === "string") {
    return padding + value;
  }
  throw new Error(`Expected string or number, got '${padding}'.`);
}

交叉类型

interface ErrorHandling {
  success: boolean;
  error?: { message: string };
}

interface ArtworksData {
  artworks: { title: string }[];
}

type ArtworksResponse = ArtworksData & ErrorHandling;

const response: ArtworksResponse = {
  success: true,
  artworks: [{ title: "Mona Lisa" }],
};

实用类型

Partial

interface User {
  id: number;
  name: string;
  age: number;
}

let partialUser: Partial<User> = {
  name: "Alice",
};

只读

let readonlyUser: Readonly<User> = {
  id: 1,
  name: "Bob",
  age: 25,
};

// readonlyUser.age = 26; // 错误:不能赋值给只读属性

Pick

type UserName = Pick<User, "name">;

let userName: UserName = {
  name: "Charlie",
};

Omit

type UserWithoutAge = Omit<User, "age">;

let userWithoutAge: UserWithoutAge = {
  id: 2,
  name: "Dave",
};

装饰器

类装饰器

function sealed(constructor: Function) {
  Object.seal(constructor);
  Object.seal(constructor.prototype);
}

@sealed
class Greeter {
  greeting: string;
  constructor(message: string) {
    this.greeting = message;
  }
  greet() {
    return "Hello, " + this.greeting;
  }
}

方法装饰器

function enumerable(value: boolean) {
  return function (
    target: any,
    propertyKey: string,
    descriptor: PropertyDescriptor
  ) {
    descriptor.enumerable = value;
  };
}

class Greeter {
  greeting: string;
  constructor(message: string) {
    this.greeting = message;
  }

  @enumerable(false)
  greet() {
    return "Hello, " + this.greeting;
  }
}

Async 和 Await

async function fetchData(url: string) {
  let response = await fetch(url);
  let data = await response.json();
  return data;
}

延伸阅读