首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >映射返回`(Wrap<A>|Wrap<B>)[]`而不是`Wrap<A|B>[]‘

映射返回`(Wrap<A>|Wrap<B>)[]`而不是`Wrap<A|B>[]‘
EN

Stack Overflow用户
提问于 2022-01-10 05:52:27
回答 3查看 56关注 0票数 0

我正试图解出密码:

代码语言:javascript
复制
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

编译器说:

代码语言:javascript
复制
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那样的联合,而不仅仅是这样。

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2022-01-10 08:16:35

在返回类型时,可以更改函数的定义,以便在T上分发。因此,这意味着当映射一个联合(例如number | string)时,您将为每个联合组成(所以Wrapped<number> | Wrapped<string>)得到一个Wrapped实例化的联合,而不是对于这个联合(所以不是Wrapped<string | number>)的Wrapped的实例化。

代码语言:javascript
复制
type DistraibutiveWrapped<T> = T extends T ? Wrap<T> : never
function wrapIt<T>(t: T): DistraibutiveWrapped<T> {
    return { value: t} as DistraibutiveWrapped<T>
}

操场连接

票数 2
EN

Stack Overflow用户

发布于 2022-01-10 06:10:23

使用显式类型检查?

代码语言:javascript
复制
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);
  }
});
票数 1
EN

Stack Overflow用户

发布于 2022-01-10 08:24:21

您可以创建额外的函数和过载

代码语言:javascript
复制
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])

游乐场

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70648319

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档