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

如何在TypeScript中无需提前声明类型,自动推导数组克隆函数的返回类型?

How to Automatically Infer Return Type for an Array Cloning Function in TypeScript

Got it, let's fix this so TypeScript automatically infers the return type without you having to explicitly pass the generic type every time.

The issue with your initial code is that TypeScript couldn't deduce the generic type T because you didn't add a type annotation to the input parameter. By typing the inputArray parameter properly, you let TypeScript figure out T from the array you pass in—no manual <number> or other type declarations needed.

Here's the corrected function:

export function someFn<T>(inputArray: T[]): T[] { 
  return [...inputArray]; 
}

// result is automatically inferred as number[]
const result = someFn([1, 2, 3]);

// It works seamlessly with other array types too:
const stringArrayResult = someFn(["apple", "banana", "cherry"]); // string[]
const mixedTypeResult = someFn([42, "hello", true]); // (number | string | boolean)[]

Why this works:

When you annotate inputArray as T[], TypeScript looks at the actual array you pass to the function and infers what T should be. For example, if you pass a number[], T becomes number, so the return type T[] automatically becomes number[].

You can even omit the explicit return type annotation if you want—TypeScript will still infer it correctly:

export function someFn<T>(inputArray: T[]) { 
  return [...inputArray]; 
}

This keeps your code clean while maintaining full type safety. The function will now always return an array with the exact same element type as the input, no manual type declarations required.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 08:35:45