【从0开始学前端】TypeScript语法总结

一、基础类型

基本类型注解

typescript 复制代码
// 基本类型
let isDone: boolean = false;
let count: number = 42;
let username: string = "Alice";

// 数组
let list1: number[] = [1, 2, 3];
let list2: Array<number> = [1, 2, 3]; // 泛型语法

// 元组 - 固定数量和类型的数组
let x: [string, number];
x = ["hello", 10]; // ✅ 正确
// x = [10, "hello"]; // ❌ 错误

// 枚举
enum Color { 
  Red,     // 0
  Green,   // 1 
  Blue     // 2
}
let c: Color = Color.Green; // 值为 1

// 任意类型
let notSure: any = 4;
notSure = "maybe a string";

// 空值
function warnUser(): void {
  console.log("This is a warning");
}

// Never 类型
function error(message: string): never {
  throw new Error(message);
}

function infiniteLoop(): never {
  while (true) {}
}

// Unknown 类型
let value: unknown;
value = "a string";
if (typeof value === "string") {
  let str: string = value; // ✅ 类型收窄后安全
}

二、类型断言

typescript 复制代码
let someValue: any = "this is a string";

// 尖括号语法
let strLength1: number = (<string>someValue).length;

// as 语法(推荐)
let strLength2: number = (someValue as string).length;

// 非空断言
let mayBeNull: string | null = "hello";
let guaranteed: string = mayBeNull!;

三、接口 (Interface)

对象接口

typescript 复制代码
interface Person {
  readonly id: number;      // 只读属性
  name: string;
  age?: number;            // 可选属性
  [propName: string]: any; // 任意属性
}

// 使用接口
let alice: Person = {
  id: 1,
  name: "Alice",
  gender: "female" // 任意属性
};

// 函数接口
interface SearchFunc {
  (source: string, subString: string): boolean;
}

let mySearch: SearchFunc = function(src, sub) {
  return src.search(sub) > -1;
};

// 可索引接口
interface StringArray {
  [index: number]: string;
}

let myArray: StringArray = ["Bob", "Fred"];

接口继承

typescript 复制代码
interface Shape {
  color: string;
}

interface Square extends Shape {
  sideLength: number;
}

let square: Square = {
  color: "blue",
  sideLength: 10
};

四、类型别名 (Type Aliases)

typescript 复制代码
// 基本类型别名
type Point = {
  x: number;
  y: number;
};

// 联合类型
type ID = number | string;

// 交叉类型
type Named = { name: string };
type Aged = { age: number };
type Person = Named & Aged;

// 复杂类型
type StringOrNumber = string | number;
type Coordinates = [number, number];
type Callback<T> = (data: T) => void;

// 接口 vs 类型别名
interface Animal {
  name: string;
}

type Bear = Animal & { 
  honey: boolean 
};

五、泛型 (Generics)

泛型函数

typescript 复制代码
function identity<T>(arg: T): T {
  return arg;
}

let output1 = identity<string>("myString");
let output2 = identity("myString"); // 类型推断

// 泛型约束
interface Lengthwise {
  length: number;
}

function loggingIdentity<T extends Lengthwise>(arg: T): T {
  console.log(arg.length);
  return arg;
}

// 多个类型参数
function swap<T, U>(tuple: [T, U]): [U, T] {
  return [tuple[1], tuple[0]];
}

泛型接口和类

typescript 复制代码
// 泛型接口
interface GenericIdentityFn<T> {
  (arg: T): T;
}

// 泛型类
class GenericNumber<T> {
  zeroValue: T;
  add: (x: T, y: T) => T;
  
  constructor(zeroValue: T, add: (x: T, y: T) => T) {
    this.zeroValue = zeroValue;
    this.add = add;
  }
}

// 泛型约束与 keyof
function getProperty<T, K extends keyof T>(obj: T, key: K) {
  return obj[key];
}

六、类 (Classes)

类的基本语法

typescript 复制代码
class Animal {
  // 成员属性
  private name: string;
  protected age: number;
  public readonly species: string;
  
  // 静态属性
  static className: string = "Animal";
  
  // 构造函数
  constructor(name: string, age: number) {
    this.name = name;
    this.age = age;
    this.species = "Animal";
  }
  
  // 方法
  public move(distance: number = 0): void {
    console.log(`${this.name} moved ${distance}m.`);
  }
  
  // 存取器
  get getName(): string {
    return this.name;
  }
  
  set setName(newName: string) {
    if (newName && newName.length > 0) {
      this.name = newName;
    }
  }
  
  // 静态方法
  static isAnimal(obj: any): boolean {
    return obj instanceof Animal;
  }
}

继承与抽象类

typescript 复制代码
// 继承
class Dog extends Animal {
  private breed: string;
  
  constructor(name: string, age: number, breed: string) {
    super(name, age);
    this.breed = breed;
  }
  
  bark(): void {
    console.log("Woof! Woof!");
    console.log(this.age); // ✅ protected 可访问
  }
}

// 抽象类
abstract class Department {
  constructor(public name: string) {}
  
  abstract printMeeting(): void; // 抽象方法
  
  printName(): void {
    console.log("Department name: " + this.name);
  }
}

class AccountingDepartment extends Department {
  constructor() {
    super("Accounting and Auditing");
  }
  
  printMeeting(): void { // 必须实现抽象方法
    console.log("The Accounting Department meets each Monday at 10am.");
  }
}

七、函数

函数类型

typescript 复制代码
// 函数声明
function add(x: number, y: number): number {
  return x + y;
}

// 函数表达式
let myAdd: (x: number, y: number) => number = function(x, y) {
  return x + y;
};

// 可选参数和默认参数
function buildName(firstName: string, lastName?: string, age: number = 18) {
  if (lastName) {
    return `${firstName} ${lastName}, age ${age}`;
  }
  return firstName;
}

// 剩余参数
function buildNames(firstName: string, ...restOfName: string[]) {
  return firstName + " " + restOfName.join(" ");
}

// 函数重载
function makeDate(timestamp: number): Date;
function makeDate(year: number, month: number, day: number): Date;
function makeDate(yearOrTimestamp: number, month?: number, day?: number): Date {
  if (month !== undefined && day !== undefined) {
    return new Date(yearOrTimestamp, month, day);
  } else {
    return new Date(yearOrTimestamp);
  }
}

八、高级类型

联合与交叉类型

typescript 复制代码
// 联合类型
let padding: string | number;

// 类型守卫
function isString(x: any): x is string {
  return typeof x === "string";
}

function processValue(value: string | number) {
  if (isString(value)) {
    return value.toUpperCase(); // 这里 value 是 string 类型
  } else {
    return value.toFixed(2);    // 这里 value 是 number 类型
  }
}

类型操作符

typescript 复制代码
// keyof 操作符
interface Person {
  name: string;
  age: number;
  location: string;
}

type PersonKeys = keyof Person; // "name" | "age" | "location"

// typeof 类型操作符
let s = "hello";
let n: typeof s; // string

// 索引访问类型
type NameType = Person["name"]; // string
type PersonPropTypes = Person[keyof Person]; // string | number

// 映射类型
type Readonly<T> = {
  readonly [P in keyof T]: T[P];
};

type Partial<T> = {
  [P in keyof T]?: T[P];
};

type Pick<T, K extends keyof T> = {
  [P in K]: T[P];
};

type Omit<T, K extends keyof any> = Pick<T, Exclude<keyof T, K>>;

条件类型

typescript 复制代码
// 基本条件类型
type TypeName<T> = 
  T extends string ? "string" :
  T extends number ? "number" :
  T extends boolean ? "boolean" :
  "object";

// 分布式条件类型
type ToArray<T> = T extends any ? T[] : never;
type StrOrNumArray = ToArray<string | number>; // string[] | number[]

// 条件类型与 infer
type ReturnType<T> = T extends (...args: any[]) => infer R ? R : any;

type MyFunc = (x: number) => string;
type Result = ReturnType<MyFunc>; // string

九、模块系统

导出与导入

typescript 复制代码
// 导出声明
export interface StringValidator {
  isAcceptable(s: string): boolean;
}

export const numberRegexp = /^[0-9]+$/;

// 导出语句
class ZipCodeValidator implements StringValidator {
  isAcceptable(s: string) {
    return s.length === 5 && numberRegexp.test(s);
  }
}
export { ZipCodeValidator };
export { ZipCodeValidator as mainValidator };

// 默认导出
export default class DefaultValidator {
  // ...
}

// 重新导出
export * from "./StringValidator";
export { ZipCodeValidator } from "./ZipCodeValidator";

导入

typescript 复制代码
// 单个导入
import { ZipCodeValidator } from "./ZipCodeValidator";

// 重命名导入
import { ZipCodeValidator as ZCV } from "./ZipCodeValidator";

// 整个模块导入
import * as validator from "./ZipCodeValidator";

// 默认导入
import DefaultValidator from "./DefaultValidator";

// 副作用导入
import "./my-module.js";

十、实用工具类型

内置工具类型

typescript 复制代码
interface Todo {
  title: string;
  description: string;
  completed: boolean;
  createdAt: number;
}

// Partial - 所有属性变为可选
type PartialTodo = Partial<Todo>;

// Readonly - 所有属性变为只读
type ReadonlyTodo = Readonly<Todo>;

// Pick - 选择部分属性
type TodoPreview = Pick<Todo, "title" | "completed">;

// Omit - 忽略部分属性
type TodoInfo = Omit<Todo, "completed" | "createdAt">;

// Record - 构建键值对类型
type PageInfo = Record<"home" | "about", { title: string }>;

// Exclude - 从联合类型中排除类型
type T0 = Exclude<"a" | "b" | "c", "a">; // "b" | "c"

// Extract - 从联合类型中提取类型
type T1 = Extract<"a" | "b" | "c", "a" | "f">; // "a"

// NonNullable - 排除 null 和 undefined
type T2 = NonNullable<string | number | undefined>; // string | number

// Parameters - 获取函数参数类型
type T3 = Parameters<(s: string, n: number) => void>; // [string, number]

// ReturnType - 获取函数返回类型
type T4 = ReturnType<() => string>; // string

// InstanceType - 获取构造函数实例类型
class C {
  x = 0;
  y = 0;
}
type T5 = InstanceType<typeof C>; // C

自定义工具类型

typescript 复制代码
// 深度只读
type DeepReadonly<T> = {
  readonly [P in keyof T]: T[P] extends object ? DeepReadonly<T[P]> : T[P];
};

// 深度可选
type DeepPartial<T> = {
  [P in keyof T]?: T[P] extends object ? DeepPartial<T[P]> : T[P];
};

// 函数参数类型
type FirstParameter<T> = T extends (first: infer P, ...args: any[]) => any ? P : never;

// 异步函数返回类型
type AsyncReturnType<T> = T extends (...args: any[]) => Promise<infer R> ? R : never;

十一、装饰器

typescript 复制代码
// 类装饰器
function sealed(constructor: Function) {
  Object.seal(constructor);
  Object.seal(constructor.prototype);
}

// 方法装饰器
function enumerable(value: boolean) {
  return function (target: any, propertyKey: string, descriptor: PropertyDescriptor) {
    descriptor.enumerable = value;
  };
}

// 属性装饰器
function format(formatString: string) {
  return function (target: any, propertyKey: string) {
    // 处理属性元数据
  };
}

// 参数装饰器
function validateParam(target: any, propertyKey: string, parameterIndex: number) {
  // 参数验证逻辑
}

// 使用装饰器
@sealed
class Greeter {
  @format("Hello, %s")
  greeting: string;

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

  @enumerable(false)
  greet(@validateParam name: string) {
    return this.greeting.replace("%s", name);
  }
}

十二、命名空间

typescript 复制代码
namespace Validation {
  export interface StringValidator {
    isAcceptable(s: string): boolean;
  }

  const lettersRegexp = /^[A-Za-z]+$/;
  const numberRegexp = /^[0-9]+$/;

  export class LettersOnlyValidator implements StringValidator {
    isAcceptable(s: string) {
      return lettersRegexp.test(s);
    }
  }

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

// 使用命名空间
let validators: { [s: string]: Validation.StringValidator } = {};
validators["ZIP code"] = new Validation.ZipCodeValidator();
validators["Letters only"] = new Validation.LettersOnlyValidator();
相关推荐
崔庆才丨静觅4 小时前
hCaptcha 验证码图像识别 API 对接教程
前端
passerby60615 小时前
完成前端时间处理的另一块版图
前端·github·web components
掘了5 小时前
「2025 年终总结」在所有失去的人中,我最怀念我自己
前端·后端·年终总结
崔庆才丨静觅5 小时前
实用免费的 Short URL 短链接 API 对接说明
前端
崔庆才丨静觅5 小时前
5分钟快速搭建 AI 平台并用它赚钱!
前端
崔庆才丨静觅5 小时前
比官方便宜一半以上!Midjourney API 申请及使用
前端
Moment6 小时前
富文本编辑器在 AI 时代为什么这么受欢迎
前端·javascript·后端
崔庆才丨静觅6 小时前
刷屏全网的“nano-banana”API接入指南!0.1元/张量产高清创意图,开发者必藏
前端
剪刀石头布啊6 小时前
jwt介绍
前端
爱敲代码的小鱼6 小时前
AJAX(异步交互的技术来实现从服务端中获取数据):
前端·javascript·ajax