Home > Blockchain >  Defining a union of objects that have the same property but different value type
Defining a union of objects that have the same property but different value type

Time:08-25

What's the idiomatic way to define an Item that can be either:

{
  title: string;
  content: string[]
}

or

{
  content: string;
}

but not:

{
  title: string;
  content: string
}

This doesn't seem to work:

type Item = {
  title: string;
  content: string[]
} | {
  content: string;
}

const item: Item = { // TypeScript doesn't complain, and I want it to
  title: "Title",
  content: "Content"
}

Playground

CodePudding user response:

Add title?: undefined to the second union element.

type Item = {
  title: string;
  content: string[]
} | {
  content: string;
  title?: undefined
}

Playground

  • Related