【问题标题】:Typescript from data object to reduced interface从数据对象到简化接口的打字稿
【发布时间】:2018-07-20 17:25:21
【问题描述】:

问题描述

我的当前数据:

{
  "field1": "value",
  "field2": 3,
  "field3": true,
  "extraField": "toRemove"
}

我定义下一个接口:

export interface MyInterface {
  field1: string;
  field2: number;
  field3: boolean;
}

目标

我需要将 my-current-data 转换或强制转换为 MyInterface(删除 extraField

避免以下解决方案

  • 删除myData.extraField
  • .map() 运算符

【问题讨论】:

  • 那个对象不是已经满足接口的条件了吗?它是接口的超集,因此任何期望该接口的东西都能够按预期正确处理myData

标签: typescript interface


【解决方案1】:
type SomeType = Omit<typeof someObject, "extraField">;

Omit typedef 可以在 typescript 2.8 更新日志中找到

【讨论】:

  • 不过你可能还有别的意思
  • lodash.omit(data, "extraField")
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-10-27
  • 2019-04-23
  • 2019-09-28
  • 2021-07-24
  • 2020-08-10
  • 2023-03-07
  • 1970-01-01
相关资源
最近更新 更多