【问题标题】:Typescript: make one of two properties optional打字稿:使两个属性之一可选
【发布时间】:2019-12-22 21:05:16
【问题描述】:

我有一个这样的界面:

export interface Picture {
  id?: string;
  src?: string;
  width: number;
  height: number;
}

我希望模型至少对idsrc 属性之一具有价值。有没有办法指定?

【问题讨论】:

    标签: typescript


    【解决方案1】:

    您可以使用union types 来完成您的任务:

    type PictureBase = {
      width: number;
      height: number;
    }
    
    export type Picture = ({ id: string } | { src: string }) & PictureBase;
    
    

    另请参阅discriminated unions上的这篇文章

    【讨论】:

    • 呃,我不确定这是否有效。根据您链接的文章,“联合类型描述了一个可以是多种类型之一的值。”
    • 不,这是 typescript 的一个特性,有时也称为有区别的联合。在这种情况下,联合指定它是 either { id: string } OR { src: string}
    • 当然,我明白了;我知道什么是歧视性工会。您只是存储对字符串的引用吗?
    • 这些东西只是类型...所以不会存储实际数据...不确定您指的是什么...
    • 嗯,一个字符串可以是可变长度的,所以大概你存储的是一个引用(而不是一个值),而联合只是给一个字符串两个不同的名字。
    【解决方案2】:

    您可以扩展这些接口。

    interface BasePicture {
      width: number;
      height: number;
    }
    
    interface IdPicture extends BasePicture {
      id: string;
    }
    
    interface SrcPicture extends BasePicture {
      src: string;
    }
    
    export type Picture = IdPicture | SrcPicture;
    

    【讨论】:

      猜你喜欢
      • 2017-03-23
      • 2022-07-27
      • 2019-04-18
      • 2018-06-05
      • 1970-01-01
      • 2016-11-01
      • 2021-12-30
      • 1970-01-01
      • 2022-12-18
      相关资源
      最近更新 更多