【问题标题】:How to specify an optional property inside another optional property?如何在另一个可选属性中指定可选属性?
【发布时间】:2021-06-18 23:14:37
【问题描述】:

我想在会议界面的另一个可选属性位置中指定可选属性 postalCode,但是当我尝试这样做时出现错误:

export interface Conference {
  name: string;
  subject: string;
  description: string;
  lecturer: string;
  type: string;
  linkToMeeting: string;
  place?: Place;
  date: string;
  time: string;
  participantsLimited: string;
}

export interface Place {
  address: string;
  city: string;
  postalCode?: string;
  country: string;
}

我收到的错误:

Type 'Conference' is not assignable to type '{ name: string; subject: string; description: string; lecturer: string; type: string; place: { address: string; city: string; country: string; postalCode?: undefined; }; linkToMeeting: string; date: string; time: string; participantsLimited: string; }'.
    Types of property 'place' are incompatible.
      Type 'Place | undefined' is not assignable to type '{ address: string; city: string; country: string; postalCode?: undefined; }'.
        Type 'undefined' is not assignable to type '{ address: string; city: string; country: string; postalCode?: undefined; }'.

我可以使用解决方法,例如将 postalCode 属性指定为“postalCode?: any”,但必须有一个选项将其指定为“字符串”和可选属性。

【问题讨论】:

  • 类型定义看起来不错。什么代码(可能是赋值语句)显示错误?
  • 你能贴出引发错误的代码吗?
  • Works in playground,所以 +1 来“显示代码”宣讲。 )

标签: typescript interface


【解决方案1】:

好吧,这是我的一个愚蠢的错误。我指定的接口没有问题。他们都还好。我试图将新会议推送到一些没有指定类型会议 [] 的数组是一个问题。感谢大家的 cmets 并让我放心,接口规范很好。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-10-15
    • 1970-01-01
    • 1970-01-01
    • 2021-08-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多