我正试图解出密码:
type Wrap<T> = {
value: T
}
function wrapIt<T>(t: T): Wrap<T> {
return { value: t}
}
const arr: Array<string|number> = ["a", 1]
const arr2: Array<Wrap<string|number>> = arr.map(wrapIt)
const arr3: Array<Wrap<string>|Wrap<number>> = arr.map(wrapIt) // <--- Doesn't compile编译器说:
Type 'Wrap<string | number>[]' is not assignable to type '(Wrap<string> | Wrap<number>)[]'.
Type 'Wrap<string | number>' is not assignable to type 'Wrap<string> | Wrap<number>'.
Type 'Wrap<string | number>' is not assignable to type 'Wrap<string>'.
Type 'string | number' is not assignable to type 'string'.
Type 'number' is not assignable to type 'string'.arr3是我需要与其他代码兼容的东西,我不拥有它。而且,在概念上,这似乎更正确。
有什么文字文字黑魔法能让它像我想的那样表现吗?现在,我将使用as进行类型转换。
编辑:Array<string|number>只是被用作一个例子,我经常使用这种模式,所以我希望解决方案适用于Array<T>,其中T是任意的,可以是像string|number那样的联合,而不仅仅是这样。
发布于 2022-01-10 08:16:35
在返回类型时,可以更改函数的定义,以便在T上分发。因此,这意味着当映射一个联合(例如number | string)时,您将为每个联合组成(所以Wrapped<number> | Wrapped<string>)得到一个Wrapped实例化的联合,而不是对于这个联合(所以不是Wrapped<string | number>)的Wrapped的实例化。
type DistraibutiveWrapped<T> = T extends T ? Wrap<T> : never
function wrapIt<T>(t: T): DistraibutiveWrapped<T> {
return { value: t} as DistraibutiveWrapped<T>
}发布于 2022-01-10 06:10:23
使用显式类型检查?
type Wrap<T> = {
value: T
}
function wrapIt<T>(t: T): Wrap<T> {
return { value: t }
}
const arr: Array<string | number> = ["a", 1]
const arr2: Array<Wrap<string | number>> = arr.map(wrapIt)
const arr3: Array<Wrap<string> | Wrap<number>> = arr.map(x => {
switch (typeof x) {
case 'string':
return wrapIt<string>(x);
case 'number':
return wrapIt<number>(x);
default:
return wrapIt(x);
}
});发布于 2022-01-10 08:24:21
您可以创建额外的函数和过载
type Wrap<T> = {
value: T
}
function wrapIt<T>(t: T): Wrap<T> {
return { value: t }
}
const arr: Array<string | number> = ["a", 1]
function map<Item,>(arr: Item[]): Array<Wrap<string> | Wrap<number>>
function map<Item,>(arr: Item[]) {
return arr.map(wrapIt)
}
// (Wrap<string> | Wrap<number>)[] which is equivalent to Array<Wrap<string> | Wrap<number>>, just different syntax
const result = map(['hello', 42])https://stackoverflow.com/questions/70648319
复制相似问题