如何在TypeScript中定义一个可以接受不同类型参数的函数?

在TypeScript中,可以使用泛型(Generics)来定义一个可以接受不同类型参数的函数。泛型允许我们在定义函数、接口或类的时候,不预先指定具体的类型,而是在使用时才指定。以下是一个例子:

```typescript
// 定义一个泛型函数
function identity(arg: T): T {
return arg;
}

// 使用泛型函数
const result1 = identity("Hello"); // T被推断为string
const result2 = identity(42); // T被推断为number

console.log(result1); // 输出: Hello
console.log(result2); // 输出: 42
```

在上面的代码中,`T` 是一个类型变量,可以代表调用时传入的任何类型。当调用 `identity` 函数时,我们显式地指定了 `T` 的具体类型,也可以让TypeScript自动推断类型:
```typescript
const inferredResult = identity(true); // T自动推断为boolean
console.log(inferredResult); // 输出: true
```

通过泛型,可以让函数更加灵活且类型安全,同时避免显式定义多个函数来处理不同的类型。

若文章对您有帮助,帮忙点个赞!

0
0
发布时间 2025-03-22 21:42:05
0 条回复(回复会通过微信通知作者)
点击加载更多评论
登录 后再进行评论
(微信扫码即可登录,无需注册)