泛型

  1. 泛型(Generics)是一种编程特性,允许你在定义函数、类或接口时不指定具体的类型,而是将类型作为参数传递,在使用时再确定具体类型。简单来说,泛型就像一个“类型占位符”,让代码更灵活、可复用,同时保持类型安全。

核心思想 类型参数化:通过泛型参数(如 T、U),让同一个函数或类处理多种类型的数据。 类型检查:编译器在实例化时检查类型,确保正确性。

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

// 使用
console.log(identity<number>(42)); // 输出: 42
console.log(identity<string>("hello")); // 输出: "hello"
  • T 是类型参数,调用时指定为 number 或 string。

interface Box { contents: T; }

const numberBox: Box = { contents: 100 }; const stringBox: Box = { contents: "apple" }; console.log(numberBox.contents); // 100 console.log(stringBox.contents); // "apple"

最后更新于

这有帮助吗?