首页 > 解决方案 > 使用打字稿接口将数组从一种类型映射到另一种类型

问题描述

我尝试将数组从一种接口类型映射到另一种接口类型,我的代码如下所示:

interface Entry { ... }

 return this.dataService.getData(id).pipe(
      map(data => ({
        ...data,
        array: data.array.map(entry => {
          if (
            instanceOfEntryB(entry) ||
            entry.options === undefined
          ) {
            return entry;
          } else {
            return <Entry & { options: SelectItem[] }>{
              ...entry,
              options: entry.options.map<SelectItem>(
                option => ({
                  description: option.label,
                  value: option.key,
                  selected: false
                })
              )
            };
          }
        })
      })),
      tap(({ array }) => {
        ctx.patchState({ array });
      })
    );

data.array键入为Entry & { options?: Option[] }并且array在州内为Entry & { options?: SelectItem[] }ctx.patchState在for 中, linterarray抛出一个错误:Type 'Option' is missing the following properties from type 'SelectItem': value, selected, description `

我怎样才能以最聪明的方式解决这个问题?

标签: typescript

解决方案


推荐阅读