[Vuejs]-Vue 3 – How to set Typescript object to one of many interfaces?

2πŸ‘

What you have is perfectly fine. In fact you did the right thing. You will always have to provide at least the properties of interface of the union type. I would suggest to do something like this

// I(nterface)User
type IUser = Baseball | Basketball | Football;

When you are unsure about what object your getting the only thing you can do is test for the properties you need.

Here is an explanation of a custom XOR type. Maybe this can help you. This will not allow you to put A, B AND C but only the properties of a single interface.

type Without < T, U > = {
  [P in Exclude < keyof T, keyof U > ] ? : never
};
type XOR < T, U > = (T | U) extends object ? (Without < T, U > & U) | (Without < U, T > & T) : T | U;

interface Profile {
  firstName: string
  lastName: string
  status: string
  stats: XOR < XOR < Baseball, Basketball > , Football >
}

export interface Baseball {
  A: string
  B: string
}

export interface Basketball {
  A: string
  C: string
}

export interface Football {
  A: string
  D: string
}



type IUser = Profile

const user: IUser = {
  firstName: 'Michael',
  lastName: 'Jordan',
  status: 'GOAT',
  stats: {
    A: '',
    B: ''
  }
};

1πŸ‘

A workaround is to move the object initialization outside of the reactive():

import { defineComponent, reactive } from 'vue'

//...

export default defineComponent({
  setup() {
    const initProfile: Baseball | Basketball | Football = {
      firstName: 'Michael',
      lastName: 'Jordan',
      status: 'GOAT',
      stats: {
        A: '1',
        C: '2',
      }
    }
    const user = reactive(initProfile)

    console.log(user.stats.C) // βœ…
  }
})
πŸ‘€tony19

Leave a comment