TypeScript是否支持参数多态?如何为数组Semigroup指定泛型参数?
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 typeTwhile enforcing that all elements in the array are of typeT. - Your own
Semigroup<A>interface is already using parametric polymorphism with the type parameterA!
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

