You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TypeScript泛型技术问询:不用泛型为何丢失类型信息及相关疑问

Hey there! Let's tackle your TypeScript generics questions one by one:

1. How do generics work in TypeScript?

Generics act like "type parameters"—they let you write flexible, reusable code that works with multiple types while keeping full type safety. Think of them as variables for types.

Instead of hardcoding a function to use string, number, or another specific type, you define a placeholder (commonly T, short for "Type") that gets replaced with the actual type when the function is called. For example, here's the generic version of your identity function:

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

If you call identity("hello world"), TypeScript infers that T is string, so the function will only accept a string input and return a string. Call it with identity(42), and T becomes number instead. This preserves type information from input to output, which is the core of how generics work.

2. Why do we lose type information when using any (as shown in the example)?

The any type is TypeScript's way of opting out of type checking entirely—it tells the compiler to ignore all type context for that value. In your example:

function identity(arg: any): any { return arg; }

If you pass a string into this function, the return value is typed as any, not string. That means you could write code like identity("hello").toFixed() (which would fail at runtime, since strings don't have a toFixed() method) and TypeScript won't flag it as an error.

We lose type information because any doesn't track the original type of the argument. Generics fix this by "remembering" the type you pass in, so the return value matches the input type exactly.

3. What can generics achieve, and can any do the same?

Generics unlock three key benefits that any can't replicate:

  • Maintain type safety: Unlike any, generics preserve type information, so TypeScript catches errors at compile time (before your code runs) and provides helpful autocompletion.
  • Build reusable, type-aware tools: You can create functions, classes, or interfaces that work with any type but enforce consistency. For example, a generic sortArray function that sorts arrays of string, number, or custom objects—while ensuring the output array has the same type as the input.
  • Define flexible, self-documenting contracts: Generics let you create types that depend on other types. For example, a generic ApiResponse<T> interface:
    interface ApiResponse<T> {
      status: number;
      data: T;
    }
    
    Now ApiResponse<User> will have data typed as User, and ApiResponse<Product> will have data typed as Product—making your code clearer and safer.

While any lets you write code that works with multiple types, it discards all type checking. You lose autocompletion, compile-time error prevention, and clear documentation of what your code expects or returns. Generics give you the flexibility of any without sacrificing TypeScript's core value: type safety.


内容的提问来源于stack exchange,提问作者El Yosemite

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 10:08:37