如何使用TypeScript将大对象映射到较小的接口

如何使用TypeScript将大对象映射到较小的接口

本文介绍了如何使用TypeScript将大对象映射到较小的接口?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个从服务器返回的对象,其中包含例如

I have an object returned from a server that contains e.g.

{
    lorem: 1,
    ipsa: [2,3],
    dolor: { sit: 'amet', consectetur: 'adipiscing'},
    elit: [{you: 'get'}, {the: 'picture'}]
}

和一个TypeScript接口

and a TypeScript interface of

export interface smallerInterface {
    ipsa: number[];
    elit: any[];
}

我要将返回的对象保存到IndexedDb中,并且不想保存界面上不存在的任何字段.

I'm saving the returned object into IndexedDb, and don't want to save any fields that are not present on the interface.

我曾尝试将 fullObject强制转换为smallInterface < smallerInterface> fullObject ,但是当将该对象保存到IndexedDb中时,它仍然包括lorem和dolor字段.

I have tried casting fullObject as smallerInterface and <smallerInterface>fullObject, but when saving this object into the IndexedDb, it is still including the fields lorem and dolor.

如何将整个对象映射到这个较小的接口(希望不编写显式映射函数),或者强制TypeScript忽略这些字段?

How can I map the full object to this smaller interface (hopefully without writing an explicit map function) or otherwise force TypeScript to ignore these fields?

推荐答案

Typescript类型不会对运行时产生影响,因此将对象强制转换为其他类型将不会在运行时对该对象产生明显影响.

Typescript types do not have a runtime impact and so casting an object to different types will have no tangible effect on that object at runtime.

TypesScript的目标之一:

One of the goals of TypesScript:

  1. 使用一致的,可完全擦除的结构类型系统.
  1. Use a consistent, fully erasable, structural type system.

我添加的

重点

如果要修改对象,则需要类型以外的代码来执行修改.鉴于无法像您所希望的那样在值和类型之间进行转换(请参见此问题进一步讨论),您将需要执行以下操作:

If you want to modify an object you need code beyond types to perform the modification. Given the inability to convert between values and types like you are looking for (see this issue for further discussion), you will need to do something like:

export interface SmallerInterface {
    ipsa: number[];
    elit: any[];
}

export const smallerKeys = ['ipsa', 'elit'];

// Later once you have a result
const result = await makeRequest();
const reducedResult = smallerKeys.reduce((obj, key) =>
    ({
        ...obj,
        [key]: result[key],
    }),
    {}
) as SmallerInterface;

这篇关于如何使用TypeScript将大对象映射到较小的接口?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-16 04:02