我有一个从服务器返回的对象,其中包含例如
{
lorem: 1,
ipsa: [2,3],
dolor: { sit: 'amet', consectetur: 'adipiscing'},
elit: [{you: 'get'}, {the: 'picture'}]
}
和一个 TypeScript 接口(interface)
export interface smallerInterface {
ipsa: number[];
elit: any[];
}
我正在将返回的对象保存到 IndexedDb 中,并且不想保存界面上不存在的任何字段。
我试过类型转换 fullObject as smallerInterface
和 <smallerInterface>fullObject
, 但是当这个对象保存到 IndexedDb 中时,它仍然包括字段 lorem 和 dolor。
如何将完整对象映射到这个较小的接口(interface)(希望无需编写显式映射函数)或以其他方式强制 TypeScript 忽略这些字段?
最佳答案
Typescript 类型没有运行时影响,因此将一个对象转换为不同类型不会在运行时对该对象产生明显影响。
goals 之一类型脚本:
- Use a consistent, fully erasable, structural type system.
我加的重点
如果你想修改一个对象,你需要类型以外的代码来执行修改。鉴于无法像您正在寻找的那样在值和类型之间进行转换(有关进一步讨论,请参阅 this issue),您将需要执行以下操作:
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 - 如何使用 TypeScript 将大对象映射到较小的界面?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50492930/