Victor Mukherjee
Victor Mukherjee

Reputation: 11095

Typescript: make one of two properties optional

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?

Upvotes: 2

Views: 3612

Answers (2)

Roberto Zvjerković
Roberto Zvjerković

Reputation: 10157

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;

Upvotes: 1

DAG
DAG

Reputation: 6994

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

Upvotes: 7

Related Questions