首页 > 解决方案 > 在 Typescript 中,检查对象是否包含接口的所有属性以及接口中未定义的其他属性的最佳方法是什么?

问题描述

例如,我想检查一个对象是否具有以下格式

interface InterA = { a: {
    b: {
      c: string //Always has this
      // May have other properties here as well, like d: number, e: string
    }
  d: string //Always has this as well
}

我希望它能够识别出这个对象属于那种类型。

{ a: {
    b: {
      c: 'Always exists'
      d: 'Exists this time
      e: 42
    }
  d: 'Also always exists'
}

我想检查一个对象是否是该对象的实例,并返回该对象及其所有参数,而不仅仅是接口中定义的参数。我在想最好的方法是使用类型保护或对 a 进行功能测试,但无法让它们中的任何一个工作。最好的方法是什么?

标签: typescript

解决方案


推荐阅读