【发布时间】:2019-06-12 10:10:16
【问题描述】:
说明
我想在 TypeScript 中定义一个通用函数,以便它将转换应用于数组参数,然后返回一个相同类型的数组。 (使用的 TypeScript 版本:v3.24)
sn-p简化代码如下:
describe("generic functions", function () {
it("should not give transpilation error", function () {
// given
function myFunction<T>(arr: T[]): T[] {
// ...... apply some transformation to the array here
return arr; // or return a copy of the array of same type
}
let arrays = [
["a"],
[1]
]; // Just for demonstration purpose, the actual input has more varieties of types
// These can be transpiled without error
myFunction(["b"]);
myFunction([2]);
arrays.map(myFunction);
// This gives transpilation error, see following for the detailed message
arrays.map(arr => myFunction(arr));
});
});
特别是我不确定为什么只有当我将函数应用于混合类型的数组并显式调用它时,TS 编译器才会识别类型。
编译错误信息为:
TS2345:'string[]| 类型的参数number[]' 不能分配给“string[]”类型的参数。 类型 'number[]' 不能分配给类型 'string[]'。 类型“数字”不可分配给类型“字符串”。
类似问题
- Assigning generics function to delegate in Typescript - 但我想保留通用签名,因为我希望我的函数更灵活
- Typescript Generic type not assignable error - 但我的函数返回的是泛型类型。
(抱歉,如果这与另一个问题重复,请告诉我 - 我曾尝试搜索但未能找到可以回答此问题的问题)
【问题讨论】:
标签: typescript generics