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

TypeScript是否支持参数多态?如何为数组Semigroup指定泛型参数?

Answers to Your TypeScript Questions

1. Does TypeScript support parametric polymorphism?

Absolutely! Parametric polymorphism in TypeScript is implemented via generics—this is one of the core features that makes TypeScript so powerful for type-safe code.

Generics let you define reusable components (like interfaces, functions, or classes) that work with multiple types without sacrificing type information. For example:

  • The built-in Array<T> is a classic example of parametric polymorphism—it works with any type T while enforcing that all elements in the array are of type T.
  • Your own Semigroup<A> interface is already using parametric polymorphism with the type parameter A!

2. How to add a generic type parameter to the array Semigroup?

Your original code uses Array<any>, which loses type safety. Instead, we can make the arraySemigroup generic so it works with arrays of a specific element type. Here are two clean approaches:

Approach 1: Generic Factory Function

This is the most flexible option because it lets you create a Semigroup for any array type on demand:

export interface Semigroup<A> { 
  append: (x: A, y: A) => A; 
}

// Generic factory function that returns a Semigroup for arrays of type T
const createArraySemigroup = <T>(): Semigroup<Array<T>> => ({
  append: (x, y) => x.concat(y)
});

// Usage example: Create a Semigroup for number arrays
const numberArraySemigroup = createArraySemigroup<number>();
numberArraySemigroup.append([1, 2], [3, 4]); // Returns [1,2,3,4] (type: number[])
// numberArraySemigroup.append([1,2], ["3"]) // Error: Type mismatch (good!)

Approach 2: Generic Semigroup Constant

If you prefer a direct generic constant (though less flexible than the factory), you can define it like this:

export interface Semigroup<A> { 
  append: (x: A, y: A) => A; 
}

const arraySemigroup: <T>() => Semigroup<Array<T>> = () => ({
  append: (x, y) => x.concat(y)
});

// Usage:
const stringArraySemigroup = arraySemigroup<string>();
stringArraySemigroup.append(["hello"], ["world"]); // Returns ["hello", "world"]

Both approaches enforce type safety: the append method will only accept arrays of the same element type, preventing accidental type mismatches that any would allow.


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 03:47:04