1
votes

I have an interface like this:

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

I want the model to have value for at least one of the id or src property. Is there a way to specify that?

2

2 Answers

5
votes

You can use union types to accomplish your task:

type PictureBase = {
  width: number;
  height: number;
}

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

See also this article on discriminated unions

0
votes

You can extend those interfaces.

interface BasePicture {
  width: number;
  height: number;
}

interface IdPicture extends BasePicture {
  id: string;
}

interface SrcPicture extends BasePicture {
  src: string;
}

export type Picture = IdPicture | SrcPicture;