not_fubar_yet
not_fubar_yet

Reputation: 372

how to define typescript interface with different schemas?

Im trying to define Consume type with 2 different payloads.

interface Eat {
  category: 'meat' | 'vegetable'
}
interface Drink {
  size: string
}
interface Consume {
   type: 'eat' | 'drink'
   payload: Eat | Drink
}

when i try if statements

function doSomething(c: Consume): string {
   if (c.type === 'Eat') {
      const e: Eat = c.payload            <----- ERRORS
      return e.category
   }
   return ''
}

errors with Type Eat | Drink is not assignable to type 'Drink'. Property 'size' is missing in type 'Eat' but required in type 'Drink'. ts(2322)

Is it possible to have 2 distinct schemas in a typescript interface Consume ?

Upvotes: 0

Views: 173

Answers (2)

not_fubar_yet
not_fubar_yet

Reputation: 372

i ended up having to rearrange it. typescript was able to detect the schema change with the format below without having to use X as typeY

type Consume = Eat | Drink

interface Eat {
  type: 'eat'
  payload: EatPayload
}
interface EatPayload {
   category: 'meat' | 'vegetable'
}

interface Drink {
  type: 'drink'
  payload: DrinkPayload
}
interface DrinkPayload {
  size: string
}

function doSomething(c: Consume): string {
   if (c.type === 'eat') {
      return c.payload.category;
   }
   return ''
}

Upvotes: 0

Syed Mohib Uddin
Syed Mohib Uddin

Reputation: 716

You can do it like this.

interface Eat {
  category: 'meat' | 'vegetable'
}
interface Drink {
  size: string
}
interface Consume {
   type: 'eat' | 'drink'
   payload: Eat | Drink
}

function doSomething(c: Consume): string {
   if (c.type === 'eat') {
      const e: Eat = c.payload as Eat;
      return e.category;
   }
   return ''
}

Upvotes: 1

Related Questions