【发布时间】:2021-08-17 18:43:36
【问题描述】:
我尝试创建一个类来抽象数组的map 函数以透明地处理单个值。
export class Container<T> {
value: T;
constructor(value: T) {
this.value = value;
}
map<U>(f: (x: T extends Array<infer R> ? R : T) => U): Container<T extends Array<any> ? Array<U> : U> {
if (Array.isArray(this.value)) {
const mapped = this.value.map(f);
return new Container(mapped); // <-- Error A here
}
return new Container<U>(f(this.value /* <-- Error B here */)); // <-- Error C here
}
unwrap(): T {
return this.value;
}
}
//Sample usage
const sayHello = (name: string) => `Hello ${name}`;
const shout = (str: string) => str.toUpperCase();
const a = new Container("Toto").map(sayHello).map(shout).unwrap() // HELLO TOTO
const b = new Container(["Harry", "Ron", "Hermione"]).map(sayHello).map(shout).unwrap() // ["HELLO HARRY", "HELLO RON", "HELLO HERMIONE"]
但是打字稿报错,我不明白为什么类型不匹配
// Error A
Type 'Container<U[]>' is not assignable to type 'Container<T extends any[] ? U[] : U>'.
Type 'U[]' is not assignable to type 'T extends any[] ? U[] : U'.ts(2322)
// Error B
Argument of type 'T' is not assignable to parameter of type 'T extends (infer R)[] ? R : T'
// Error C
Type 'Container<U>' is not assignable to type 'Container<T extends any[] ? U[] : U>'.
Type 'U' is not assignable to type 'T extends any[] ? U[] : U'
我现在可以用any“修复”它,但要寻找更清洁的解决方案
【问题讨论】:
-
new Container(...)真的比[...]干净吗?为什么不把东西包装在一个数组而不是一个自定义类中? -
你找到this question了吗?我想这是同一个问题,但我不是 100% 确定
-
@A_A 谢谢,这解释了为什么我的解决方案不起作用!
标签: typescript