【问题标题】:Convert object to array with map with typings in TS使用 TS 中的类型将对象转换为数组
【发布时间】:2019-11-27 08:47:15
【问题描述】:

我正在尝试将来自 Firebase 的值对象转换为类型化的值数组:

const snapshot = await db.teams().once('value');
const teams: Array<ITeam> = Object.entries(snapshot.val()).map(
    ([id, { identifier, name }]): ITeam => {
        return { identifier, name, id };
    }
);

类型的建模如下:

export interface ITeam extends ITeamEntry {
    id: string;
}

export interface ITeamEntry {
    identifier: string;
    name: string;
}

但我收到如下错误:

Property 'identifier' does not exist on type 'unknown'.
Property 'name' does not exist on type 'unknown'.

我不知道如何解决这个问题。

【问题讨论】:

  • 不应该ILeagueITeam 的类型属性吗?

标签: javascript typescript firebase-realtime-database


【解决方案1】:

val 可能是具有unknown 属性的对象。为了能够访问属性,您可能需要将 val 断言为 Record&lt;string, ITeam&gt;

const teams: Array<ITeam> = Object.entries(snapshot.val() as Record<string, ITeam>).map(
    ([id, { identifier, name }]): ITeam => {
        return { identifier, name, id };
    }
);

【讨论】:

  • 谢谢!我错过了Record 类型。我不知道。
猜你喜欢
  • 2021-09-09
  • 2017-12-27
  • 1970-01-01
  • 2020-12-28
  • 1970-01-01
  • 2014-10-10
  • 2019-01-26
  • 2020-07-31
  • 2021-07-01
相关资源
最近更新 更多